游戏开发人员可以使用光线投射,用于像瞄准,确定视线,测量距离之类的动作。Unity当中的Raycast的重载有很多。现在展示最常用的2中方法

bool Raycast( Vector3 origin , Vector3 direction , float distance ,LayerMask mask );

参数解释
 origin : 是光线的开始位置
 direction : 光线的方向
 distance : 光线行进的距离(可为null)
 mask : 确定光线会撞上哪一层(可为null)


如果要确定摄像机前确定是否有某个物体,可以用如下代码

void Update(){
    if (Physics.Raycast(transform.position , transform.forward , 10 )){
        print("there is something in front of the camera!");
    }
}

注意此代码放在camera中


另一个

bool Raycast( Vector3 origin , Vector3 direction , out RaycastHit hit , float distance );

这个重载方法使用了一个RaycastHit类型的参数 , 它是光线碰撞到的对象

void Update(){
    float dirX = Input.GetAxis("Mouse X");
    float dirY = Input.GetAxis("Mouse Y");
    transform.Rotate(dirY , -dirX , 0 );
    UptateRaycastHit();
}
void UpdateRaycastHit(){
    RayCastHit hit;
    if( Physics.Raycast( transform.position , transform.forward , out hit ) ){
        Distroy( hit.collider.gameObject )
    }
}