Unity 射线
2017-02-27 本文已影响114人
U3D界金城武
1,摄像机射线:
Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Debug.DrawLine(ray.origin, hit.point); //显示出射线
//Debug.DrawLine(transform.position, hit.point, Color.red);
if (hit.collider.gameObject.name == "dogpoint")
{
play.dog1();
hit.collider.gameObject.SetActive(false); //碰到的物体关闭
}
}
2, 物体发射射线:
//通过标签指定
//ray = new Ray(GameObject.FindGameObjectWithTag("Player").transform.position, GameObject.FindGameObjectWithTag("Player").transform.forward);
//通过cam 坐标
//ray = new Ray(game.position, game.forward);
Vector3 fwd = transform.TransformDirection(Vector3.forward);
RaycastHit hit;
if (Physics.Raycast(transform.position,fwd,out hit))
{
Debug.DrawLine(ray.origin, hit.point); //显示出射线
//Debug.DrawLine(transform.position, hit.point, Color.red);
if (hit.collider.gameObject.name == "dogpoint")
{
play.dog1();
hit.collider.gameObject.SetActive(false); //碰到的物体关闭
}
}
3, 点击发出射线:
if (Input.GetMouseButtonDown(0))
{ //首先判断是否点击了鼠标左键
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //定义一条射线,这条射线从摄像机屏幕射向鼠标所在位置
RaycastHit hit; //声明一个碰撞的点(暂且理解为碰撞的交点)
if (Physics.Raycast(ray, out hit)) //如果真的发生了碰撞,ray这条射线在hit点与别的物体碰撞了
{
if (hit.collider.gameObject.name == "Qingting") //如果碰撞的点所在的物体的名字是“StartButton”(collider就是检测碰撞所需的碰撞器)
{
print("蜻蜓");
play = ZT.s1;
}
}
}
}