標籤:raycast 光線投射
遊戲開發人員可以使用光線投射,用於像瞄準,確定視線,測量距離之類的動作。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 ) }}
本文出自 “Better_Power_Wisdom” 部落格,請務必保留此出處http://aonaufly.blog.51cto.com/3554853/1701717
Raycasting光線投射