2014-11-25 27 views
-2

所以我明白涉及的数学,只是对如何实现它有点困惑。我把它抓住gameobjects一定距离已经:在一定的距离和角度内选择GameObjects

 GameObject[] nodesInView = GameObject.FindGameObjectsWithTag ("Node"); 
     List<GameObject> listOfNodesInView = new List<GameObject>(); 
     foreach (GameObject node in nodesInView) { 
      float dist = (player.transform.position - node.transform.position).magnitude; 
      if(dist < 100) 
      { 
       listOfNodesInView.Add (node); 
      } 

     } 

但是,这是给我的是360度的角度:

enter image description here

请原谅我的画,但它说明它在做什么。但现在,我将如何限制基于角度变量的搜索?

enter image description here

*编辑THETA =值我选择,并不看重选择。

而且是要知道,红点代表的起源是很重要的,绿色的代表正在收集什么,橙色代表节点

回答

0

要搜索一定距离内游戏物体和角度我搞砸周围有很多和找到了我认为可行的解决方案:

GameObject[] nodesInView = GameObject.FindGameObjectsWithTag ("Node"); 
    List<GameObject> listOfNodesInView = new List<GameObject>(); 
    foreach (GameObject node in nodesInView) { 
     float dist = (player.transform.position - node.transform.position).magnitude; 
     if(dist < 300) 
     { 
      Vector3 dir = player.transform.position - node.transform.position; 
      float angle = Mathf.Atan2 (dir.z, dir.x) * Mathf.Rad2Deg; 
      if(angle > 45 && angle < 120) 
       listOfNodesInView.Add (node); 
     } 

    } 

这是在一定距离内和两个角度之间搜索gameobject。 (见第二视觉图片)

0

下面是我用什么:

// From me to another game object returns it's distance and relative angle I'd need to turn to face it 
private bool CalculateDistanceAndDirectionToTarget(Transform target, out float distance, out float angle) 
{ 
    if (target == null) { return false; } 

    // distance from me 
    distance = Vector3.Distance(transform.position, target.position); 

    // angle from me 
    Vector3 deltaPosition = target.position - transform.position; 
    // Get the delta angle from our current forward to turn towards the target. 
    // Note: This is an absolute value and the smallest angle 
    // Ref: http://answers.unity3d.com/questions/376921/im-having-problems-checking-of-my-ai-can-see-me-c.html 
    float angle = Vector3.Angle(deltaPosition, transform.forward); 
    // To determine if we need to turn left/right, use the cross product to calculate the sign 
    // Ref: http://answers.unity3d.com/questions/181867/is-there-way-to-find-a-negative-angle.html 
    Vector3 cross = Vector3.Cross(deltaPosition, transform.forward); 
    if (cross.y < 0) 
    { 
     angle = -angle; 
    } 

    return true; 
} 

// Determine if I can see the target given a distance and angle I can see 
public bool IsWithinSight(Transform target, float maxDistance, float maxAngle) 
{ 
    float angle = 0f; 
    float distance = 0f; 

    if (CalculateDistanceAndDirection(target, out distance, out angle)) 
    { 
      if (distance < maxDistance && Mathf.Abs(angle) < maxAngle) 
      { 
       return true; 
      } 
    } 

    return false; 
} 

然后你就可以循环通过某种类型的所有游戏对象进行检查。

相关问题