2.2.4 ScreenToViewportPoint方法:坐标系转换
基本语法:public Vector3 ScreenToViewportPoint(Vector3 position);
其中参数position为屏幕参考点。
功能说明:此方法的功能是实现坐标点position从屏幕坐标系向摄像机视口的单位化坐标系转换。参考点position的x和y分量为屏幕的实际坐标值,单位为像素,z值无效。
实例演示:下面通过实例演示方法ScreenToViewportPoint的使用。
using UnityEngine;
using System.Collections;
public class ScreenToViewportPoint_ts : MonoBehaviour
{
void Start()
{
transform.position = new Vector3(0.0f, 0.0f, 1.0f);
transform.rotation = Quaternion.identity;
//从屏幕的实际坐标点向视口的单位化比例值转换
Debug.Log("1:" + camera.ScreenToViewportPoint(new Vector3(Screen.width / 2.0f, Screen.height / 2.0f, 100.0f)));
//从视口的单位化比例值向屏幕的实际坐标点转换
Debug.Log("2:" + camera.ViewportToScreenPoint(new Vector3(0.5f, 0.5f, 100.0f)));
Debug.Log("屏幕宽:" + Screen.width + " 屏幕高:" + Screen.height);
}
}
在这段代码中,首先重置了摄像机的position和rotation,然后调用方法ScreenToViewportPoint将屏幕的正中间位置转换为视口比例值并打印出来,接着调用方法ViewportToScreenPoint将视口的中间位置转换为屏幕的实际像素值并打印出来,最后打印出了屏幕的宽度和高度,程序运行结果如图2-12所示。
本文章内容摘自图书《Unity API解析》,源码下载地址:http://www.ituring.com.cn/book/1474