Unity學習筆記005.射線點選事件(PC/Mobile)
阿新 • • 發佈:2018-12-07
預處理,判斷當前平臺
void LateUpdate()
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
PC();
#endif
#IF UNITY_EDITOR || UNITY_ANDROID
Mobile();
#endif
}
[注]
if的作用是程式流控制,會直接編譯、執行。
#if是對編譯器的指令,其作用是告訴編譯器,有些語句行希望在條件滿足時才編譯。
射線點選事件(PC)
private void PC()
{
if(Input.GetMouseButtonDown(0)) // 如果滑鼠左鍵按下
{
RaycastHit hitInfo;
// 射線從滑鼠點擊出射出
Ray ray = Camera.ScreenPointToRay(Input.mousePosition);
Transform targetTransform = null;
// 在maxDistance長度之內,射線ray與第一個物件(無論層級)進行的物理碰撞的資訊,儲存在hitInfo中;如果有碰撞物體,返回true, 反之false;
if(Physics.Raycast(ray, out hitInfo, Mathf.Infinity, -1))
{
// 獲取碰撞到的物體資訊
targetTransform = hitInfo.collider.transform;
}
if(targetTransform != null)
{
DoSomething();
}
}
}
射線點選事件(Mobile)
private void Mobile()
{
// 單指觸控
if(Input.touchCount == 1)
{
// 儲存觸控點資訊
Touch touch = Input.GetTouch(0);
// 如果手指觸控式螢幕幕,但並未移動,不做處理
if(touch.phase == TouchPhase.Stantionary)
return ;
// 判斷是否點選在UI上
if(EventSystem.current.IsPointerOverFameObject(touch.fingerID))
return;
RaycastHit hitInfo;
Ray ray = Camera.ScreenPointToRay(touch.position);
Transform targetTransform = null;
if(Physics.Raycast(ray, out hitInfo, Mathf.Infinity, -1))
{
targetTransform = hitInfo.collider.transform;
}
if(targetTranform != null)
{
DoSomething();
}
}
}