Unity WorldToScreenPoint坐标变换

来源:互联网 发布:ps制作淘宝宝贝主图 编辑:程序博客网 时间:2024/06/04 18:07

功能:实现标签跟随物体运动,标签是一个Prefab,由底图和文字组成。Dota2中英雄血条的实现也是这种原理。

说到底就是标签根据物体位置不间断刷新自己的坐标值,3D—>2D—>3D;

先来了解一下Unity#D中的坐标系统:

1.World Space(世界坐标)

我们在场景中添加物体(如:Cube),他们都是以世界坐标显示在场景中的。只要脚本挂在该物体上,transform.position可以获得该位置坐标。

2.Screen Space(屏幕坐标)

以像素来定义的,以屏幕的左下角为(0,0)点,右上角为(Screen.width,Screen.height),z是坐标到摄像机的距离。如Input.MousePosition属于屏幕坐标。

再来了解一下使用到的函数:

Camera.WorldToScreenPoint();

原型:public Vector3 WorldToScreenPoint(Vector3 position);

返回值:Vector3 中x,y是屏幕中的位置。z是坐标到摄像机的距离

重点在于各种坐标的转换:

using UnityEngine;
using System.Collections;
namespace ROAM
{
    [ExecuteInEditMode]

    //ExecuteInEditMode属性的作用是在EditMode下也可以执行脚本。Unity中默认情况下,脚本只有在运行的时候才被执行,加上此属性后,不运行程      序,也能执行脚本。

    public class moveLabel : MonoBehaviour
    {
        Camera worldCam = null;  //渲染3D模型的相机
        Camera uiCamera = null;   //渲染标签的相机
        public GameObject PopTagPrefab;//这里要把做好的标签Prefab拖进来
        // Use this for initialization
        void Start()
        {
            GameObject worldCam1 = GameObject.Find("Main Camera");
            worldCam = worldCam1.GetComponent<Camera>();
            GameObject uiCam = GameObject.Find("UI Root/Camera");
            uiCamera = uiCam.GetComponent<Camera>();
        }


        // Update is called once per frame
        void Update()
        {
            //Debug.Log(Screen.width);
            Vector3 vPos = worldCam.WorldToScreenPoint(transform.position);
            Vector3 temp = uiCamera.ScreenToWorldPoint(vPos);
            temp.z = 0;
            if (null != PopTagPrefab)
            {
                PopTagPrefab.transform.position = temp;
            }
        }
    }
}



0 0