所以我理解所涉及的数学,对如何实现它有点困惑。我已经抓住了一定距离的游戏对象:
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度的角度:
请原谅我的绘画,但它正在说明它在做什么。但是现在,我如何根据角度变量限制搜索?
* EDIT Theta =我选择的值,而不是值选择。
同样重要的是要知道红点代表原点,绿色代表收集的内容,橙色代表节点
答案 0 :(得分: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);
}
}
这是在一定距离内搜索两个角度之间的游戏对象。 (见第二张图片)
答案 1 :(得分: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;
}
然后你可以循环浏览某种类型的所有游戏对象。