您的位置:首页 > 其它

Raycasting光线投射

2015-10-10 23:50 162 查看
游戏开发人员可以使用光线投射,用于像瞄准,确定视线,测量距离之类的动作。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 )
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Raycast 光线投射