1、摄像机发出射线,碰撞到plane。
代码:
void Start ()
{
UIEventListener.Get(this.gameObject).onPress = Press;
}
public void Press (GameObject go, bool pressed)
{
if(pressed)
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit))
{
Debug.LogError(hit.transform.tag);
Debug.LogError(hit.distance);
}
}
}
2、任意物体发射一条射线:
代码:
public Transform btn;
void Start ()
{
UIEventListener.Get(btn.gameObject).onPress = Press;
}
public void Press (GameObject go, bool pressed)
{
if(pressed)
{
RaycastHit hit;
if (Physics.Raycast(this.transform.position, this.transform.forward, out hit))
{
Debug.LogError(hit.transform.tag);
Debug.LogError(hit.distance);
}
}
}
3、平面和射线的交点,以及点到平面的距离(有符号的距离),因为平面有法线,点在平面的前面还是后面。
代码:
public Transform btn;
void Start ()
{
UIEventListener.Get(btn.gameObject).onPress = Press;
}
public void Press (GameObject go, bool pressed)
{
if(pressed)
{
//射线到平面的交点
Plane plane = new Plane(Vector3.forward, Vector3.zero);
Ray ray = new Ray(new Vector3(0, 0, 1), new Vector3(1, 0, -1));
float distance = 0;
if (plane.Raycast(ray, out distance))
{
Debug.LogError(distance);
}
//点到平面的距离
distance = plane.GetDistanceToPoint(new Vector3(0, 0, -1));
Debug.LogError(distance);
}
}
3、从摄像机发出一条到屏幕上的点的射线
这里有两个点,一个是摄像机所在的位置,另外一个是鼠标点击屏幕的位置,两个点确定了一条射线。
public void Update()
{
if(Input.GetMouseButtonDown(0))
{
Debug.LogError(Input.mousePosition);
Ray ray = UICamera.currentCamera.ScreenPointToRay(Input.mousePosition);
Debug.LogError(ray.origin);
Debug.LogError(ray.direction);
Debug.DrawRay(ray.origin, ray.direction * 10, Color.yellow);
}
}