利用射线进行碰撞检测做射击效果

     先定义Camera组建的对象  private Camera _camera;,然后在Start方法中获取当前模型上的摄像机组建Camera,  


_camera = GetComponent<Camera> ();并且设定光标为锁定状态,然后隐藏屏幕中心的默认光标Cursor.lockState = CursorLockMode.Locked;Cursor.visible = false;

接着在当界面中让射线的对准摄像机的终点并且让它在中心显示一个*号;


渲染和处理GUI事件时调用。

This means that your OnGUI implementation might be called several times per frame (one call per event). For more information on GUI events see the Event reference. If the MonoBehaviour's enabled property is set to false, OnGUI() will not be called.

这意味着你的OnGUI程序将会在每一帧被调用。要得到更多的GUI事件的信息查阅Event。如果Monobehaviour的enabled属性设为false,OnGUI()将不会被调用。

接着让我们来写射线的获取和碰撞:

当点击鼠标左键时

if(Input.GetMouseButtonDown(0)){

给射线一个点让它位于中心

扫描二维码关注公众号,回复: 1501174 查看本文章

Vector3 point = new Vector3 (_camera.pixelWidth/2,_camera.pixelHeight/2,0);

//获取射线
   Ray ray = _camera.ScreenPointToRay (point);
   //射线碰撞
   RaycastHit hit;

判断射线是否发生碰撞

if(Physics.Raycast(ray,out hit)){
    GameObject   target = hit.transform.gameObject;//获取碰撞的目标
    hit   hitTarget = target.GetComponent<hit> ();//获取当前物体上的碰撞组建
    if (hitTarget != null) {//如果碰撞目标不为空时
     hitTarget.Hit ();//发生碰撞
    } else {否则执行协程
     //协程
     StartCoroutine (CreatandDestroy(hit.point));
    }
   }

}


//协程
 private IEnumerator CreatandDestroy(Vector3 P){P所拥有的值时point的传过来的
  GameObject sphere = GameObject.CreatePrimitive (PrimitiveType.Sphere);//创建一个对象,并且类型为球体PrimitiveType.Sphere
  sphere.transform.position = P;//球体生成的位置
  yield return new WaitForSeconds (1);//一秒后执行销毁代码Destroy (sphere);
  Destroy (sphere);
 }

完成后该代码附加在摄像机上



还需创建另一个C#脚本来接收碰撞后发生的事件,将你希望实现发射出子弹命中目标后将会发生的功能或效果写进去,并将该代码附加到目标身上即可。





猜你喜欢

转载自blog.csdn.net/qq_27748027/article/details/76818854