正如题目所说,ScreenPointToRay可以计算从Camera的近视口nearClip向前发射一条射线到屏幕上的点的坐标。
函数原型为:
public Ray ScreenPointToRay(Vector3 position);
其中position为屏幕位置的参考点,它是用实际像素值的方式来决定Ray到屏幕的位置。参考点position的x轴分量或y轴分量从0增长到最大值时,Ray从屏幕一边移动到另一边。当Ray未碰到任何物体时,hit.point范围值为Vector3.zero即Vector3(0,0,0)。参考点的z轴分量值无效。
using UnityEngine; using System.Collections; public class ScreenPointToRay_ts : MonoBehaviour { Ray ray; RaycastHit hit; //记录射线到屏幕上的实际像素坐标 Vector3 v3 = new Vector3(Screen.width / 2.0f, Screen.height / 2.0f, 0.0f); Vector3 hitPoint = Vector3.zero; // Use this for initialization void Start () { } // Update is called once per frame void Update () { //控制射线不断进行左右方向的扫描 v3.x = v3.x >= Screen.width ? 0.0f : v3.x + 1.0f; ray = camera.ScreenPointToRay(v3); if(Physics.Raycast(ray,out hit,100.0f)) { Debug.DrawLine(ray.origin, hit.point, Color.green); Debug.Log("射线探测到的物体名称: " + hit.transform.name); } } }
运行结果为: