您的位置:首页 > 移动开发 > Unity3D

Unity3D中Camera类ScreenToWorldPoint方法使用解析

2014-09-19 21:45 961 查看
2.2.5 ScreenToWorldPoint方法:坐标系转换

基本语法:public Vector3 ScreenToWorldPoint(Vector3 position);

其中参数position为屏幕参考点。

功能说明:此方法的作用是将参考点position从屏幕坐标系转换到世界坐标系。此方法与方法ViewportToWorldPoint功能类似,只是此方法的参考点position中各个分量值都为实际单位像素值,而非比例值。

例如执行如下代码后,

Vector v3= camera. ScreenToWorldPoint (ps);//ps为已知参考点

v3的各个分量值为:

v3.x= camera.transform.position.x+ps.z*asp* tan(e/2);

v3.y= camera.transform.position.y+ ps.z*tan(e/2);

v3.z= camera.transform.position.z +ps.z;

其中ps为已知参考值,e为摄像机的视口夹角fieldOfView的值,asp为摄像机视口的宽高比例值aspect。更多内容请参考方法ViewportToWorldPoint的功能说明。

实例演示:下面通过实例演示方法ScreenToWorldPoint的使用。

using UnityEngine;
using System.Collections;

public class ScreenToWorldPoint_ts : MonoBehaviour
{
void Start()
{
transform.position = new Vector3(0.0f, 0.0f, 1.0f);
camera.fieldOfView = 60.0f;
camera.aspect = 16.0f / 10.0f;
//Z轴前方100处对应的屏幕的左下角的世界坐标值
Debug.Log("1:" + camera.ScreenToWorldPoint(new Vector3(0.0f, 0.0f, 100.0f)));
//Z轴前方100处对应的屏幕的中间的世界坐标值
Debug.Log("2:" + camera.ScreenToWorldPoint(new Vector3(Screen.width / 2.0f, Screen.height / 2.0f, 100.0f)));
//Z轴前方100处对应的屏幕的右上角的世界坐标值
Debug.Log("3:" + camera.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, 100.0f)));
}
}


在这段代码中,首先重置了摄像机的位置position、视口夹角fieldOfView和视口宽高比aspect,然后调用方法ScreenToWorldPoint分别计算和打印出了视口前方100米处的左下角、中间和右上角的坐标值,程序运行结果如图2-13所示。

本文章内容摘自图书《Unity API解析》,源码下载地址:http://www.ituring.com.cn/book/1474
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: