XNA Field of View in 2D

I am working on a 2D game in flocking based XNA. I implemented the Craig Reynold flocking technique, and now I want to dynamically assign a leader to the group in order to guide it toward the goal.

To do this, I want to find a game agent who has no other agents in front of him and make him a leader, but I'm not sure about the math for this.

I currently have:

Vector2 separation = agentContext.Entity.Position - otherAgent.Entity.Position; float angleToAgent = (float) Math.Atan2(separation.Y, separation.X); float angleDifference = Math.Abs(agentContext.Entity.Rotation - angleToAgent); bool isVisible = angleDifference >= 0 && angleDifference <= agentContext.ViewAngle; 

agentContext.ViewAngle - these are the values โ€‹โ€‹of the radians that I played with in order to try to get the right effect, but this basically leads to the fact that all agents are appointed leaders.

Can someone point me in the right direction to determine if the object is in the โ€œconeโ€ of the vision of another object?

+4
source share
2 answers

You need to normalize the entrance to the Atan2 function. You should also be careful when subtracting angles, because the result may be outside the range pi to -pi. I prefer using direction vectors rather than angles, so you can use the point product operation for things like this, which tend to be faster, and you donโ€™t have to worry about angles outside the canonical range.

The following code should achieve the result you execute:

  double CanonizeAngle(double angle) { if (angle > Math.PI) { do { angle -= MathHelper.TwoPi; } while (angle > Math.PI); } else if (angle < -Math.PI) { do { angle += MathHelper.TwoPi; } while (angle < -Math.PI); } return angle; } double VectorToAngle(Vector2 vector) { Vector2 direction = Vector2.Normalize(vector); return Math.Atan2(direction.Y, direction.X); } bool IsPointWithinCone(Vector2 point, Vector2 conePosition, double coneAngle, double coneSize) { double toPoint = VectorToAngle(point - conePosition); double angleDifference = CanonizeAngle(coneAngle - toPoint); double halfConeSize = coneSize * 0.5f; return angleDifference >= -halfConeSize && angleDifference <= halfConeSize; } 
+1
source

I think you want to check the +/- angle, and not just + (i.e. angleDifference >= -ViewAngle/2 && angleDifference <= ViewAngle/2 ). Or use an absolute value.

+1
source

All Articles