http://www.xiaobao1993.com/231.html
射線是一個無窮的線,開始於origin並沿着direction方向。
當射線碰到物體后。它就會停止發射。
在屏幕中拉一個CUBE,並用鼠標點擊它
using UnityEngine;
using System.Collections;
public class TestRay : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButton(0))
{
Debug.Log("xxxxxxxxxxxxxxxxxxxxxx");
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//從攝像機發出到點擊坐標的射線
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
Debug.DrawLine(ray.origin, hitInfo.point);//划出射線,在scene視圖中能看到由攝像機發射出的射線
GameObject gameObj = hitInfo.collider.gameObject;
if (gameObj.name.StartsWith("Cube") == true)//當射線碰撞目標的name包含Cube,執行拾取操作
{
Debug.Log(gameObj.name);
}
}
}
}
}
