2019年2月19日 星期二

Unity 射線扇形

以下程式碼先以DrawLin方式呈現射線大概位置
再處理射線部分。

若是成功會呈現出以下圖片:




-----------------------------------
static public void LookAround(Transform targets)
{
    float viewRadius = 10f; // 視野距離
    float viewAngleStep = 20; // 射線數量
    // 射線從左邊開始,角度為-45;
    Vector3 forwardLeft = Quaternion.Euler(0, -45, 0) * targets.forward * viewRadius;
        
    for(int i =0; i <= viewAngleStep; i++){
            
     // 射線由forwardLeft基礎點偏轉
 Vector3 vector = Quaternion.Euler(0, (90 / viewAngleStep)* i, 0) * forwardLeft;
        // targets位置 + vector = 射線最終位置     
        Vector3 pos = targets.position + vector;
 Debug.DrawLine(targets.position, pos, Color.red);
    }
}
------------------------------------------
以下是透過射線,以DrawLin方式呈現
如果成功會呈現以下圖:










------------------------------------------
static public void LookAround(Transform targets)
{
    float viewRadius = 10f; // 視野距離
    float viewAngleStep = 20; // 射線數量
    // 射線從左邊開始,角度為-45;
    Vector3 forwardLeft = Quaternion.Euler(0, -45, 0) * targets.forward * viewRadius;
        
    for(int i =0; i <= viewAngleStep; i++){
            
     // 射線由forwardLeft基礎點偏轉
 Vector3 vector = Quaternion.Euler(0, (90 / viewAngleStep)* i, 0) * forwardLeft;

   // 建立射線
        Ray ray = new Ray(targets.position, vector);
        RaycastHit hits = new RaycastHit();

 // Layer 碰撞偵測
        int mask = LayerMask.GetMask("Point");
        Physics.Raycast(ray, out hits, mask);

        // targets位置 + vector = 射線最終位置     
        Vector3 pos = targets.position + vector;
 Debug.DrawLine(targets.position, pos, Color.red);

 // 射線碰撞到,就當碰撞點
 if(hits.transform != null)
     pos = hits.point;

 Debug.DrawLine(targets.position, pos, Color.red);

 // 碰到敵人在處理
 if(hits.transform != null && hits.transform.gameObject.layer.Equals(LayerMask.NameToLayer("Point")))
 {
     // 射線長度
     Vector3 dis  = targets.position - hits.collider.transform.position;
     float value = dis.sqrMagnitude;
     Debug.Log(hits.collider.gameObject + "距離: " + value);
  }
 }
}

沒有留言:

張貼留言