Unity 射線檢測(RayCast)


Raycast 射線檢測

 Unity 中提供了一種控制方案,用來檢測鼠標點在屏幕上后,具體點在 Unity 場景中,三維世界的哪個點上

 這種解決方案,就是射線檢測:

 通過鼠標點擊屏幕,由屏幕上的點向Unity三維直接發射一條無限長的射線

 當檢測到碰撞物體后,便會返回被碰撞物體的所有信息,以及交點信息等等... ...

常用射線檢測方法

1. 普通射線檢測(一般用於檢測某一個物體)

1    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
2    Debug.DrawRay(ray.origin, ray.direction, Color.red);
3    RaycastHit hit;
4    if (Physics.Raycast(ray, out hit, int.MaxValue, 1 << LayerMask.NameToLayer("layerName")))
5    {
6       Debug.Log("檢測到物體!");
7    }

2. 直線射線檢測多個物體

 1    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
 2    Debug.DrawRay(ray.origin, ray.direction, Color.red);
 3    RaycastHit[] hit = Physics.RaycastAll(ray, Mathf.Infinity, 1 << LayerMask.NameToLayer("layerName"));
 4    if (hit.Length > 0)
 5    {
 6        for (int i = 0; i < hit.Length; i++)
 7        {
 8            Debug.Log("檢測到物體:" + hit[i].collider.name);
 9        }
10    }

3. 球形射線檢測(一般用於檢測周邊物體)

1    int radius = 5;
2    Collider[] cols = Physics.OverlapSphere(this.transform.position, radius, LayerMask.NameToLayer("layerName"));
3    if (cols.Length > 0)
4    {
5        for (int i = 0; i < cols.Length; i++)
6        {
7            Debug.Log("檢測到物體:" + cols[i].name);
8        }
9    }

畫出球形檢測范圍的方法:

1     private void OnDrawGizmos()
2     {
3         Gizmos.DrawWireSphere(this.transform.position, 5);
4     }

簡單的實例

 創建地板和小球,構建簡單的測試場景

 將腳本掛載到空物體上,並在 Inspector 面板上對 Ball 進行賦值

 1 using UnityEngine;
 2 
 3 public class RayCast : MonoBehaviour
 4 {
 5     public Transform Ball; //小球
 6 
 7     //設置射線在Plane上的目標點target
 8     private Vector3 target;
 9 
10     void Update()
11     {
12         if (Input.GetMouseButton(1))
13         {
14             object ray = Camera.main.ScreenPointToRay(Input.mousePosition);
15             RaycastHit hit;
16             bool isHit = Physics.Raycast((Ray)ray, out hit);
17             Debug.DrawLine(Input.mousePosition, hit.point, Color.red);
18             if (isHit)
19             {
20                 Debug.Log("坐標為:" + hit.point);
21                 target = hit.point;
22             }
23         }
24         //如果檢測到小球的坐標 與 碰撞的點坐標 距離大於0.1f,就移動小球的位置到碰撞的點
25         Ball.position = Vector3.Distance(Ball.position, target) > 0.1f ? Vector3.Lerp(Ball.position, target, Time.deltaTime) : target;
26     }
27 
28     /// <summary>
29     /// 移動方法
30     /// </summary>
31     /// <param name="target"></param>
32     void Move(Vector3 target)
33     {
34         if (Vector3.Distance(Ball.position, target) > 0.1f)
35         {
36             Ball.position = Vector3.Lerp(Ball.position, target, Time.deltaTime);
37         }
38         else
39             Ball.position = target;
40     }
41 }

 測試效果:

 射線檢測的好處在於,發出的射線與帶有Collider 組件的物體都會發生碰撞,並且可以返回各種信息

 例如:被碰撞物體的位置、名稱、法線等等一系列的數據

 另外還可以自定義發出射線的距離、影響到的圖層等等

 

 

 

 

 

*** |  以上內容僅為學習參考、學習筆記使用  | ***


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM