Sign in to follow this  
josh123

Beginning AI With XNA

Recommended Posts

josh123    122
I'm just starting to build my first real game with XNA. It will be a 2d stealth game where you have to avoid enemy guards. My question is, how can I make it so the guards only "see" the direction that they are facing on the screen? I imagine there is a grid or something I can reference for the entire screen, but I haven't been able to find out how to use it yet. If anyone could point me in the right direction I would appreciate it. Thanks!

Share this post


Link to post
Share on other sites
epsylon    182
Have you ever played Commandos ?
In Commandos, the guards have a "triangle of view" (2D Projection of a Cone on the ground). Detecting an enemy is then a simple is-centroid-of-the-player-model-into-the-triangle question.

Share this post


Link to post
Share on other sites
remigius    1172
You can also use the dotproduct as an easy and computationally cheap way to determine this. I typically use something along these lines for a rough visibility test:

[source lang=csharp]
Vector2 guardPos = new Vector2(0, 0); // or whatever is applicable
Vector2 guardFacing = new Vector2(1, 0); // looking 'right', along the positive x axis

Vector2 targetPos = new Vector2(-1, 0); // 'behind' the guard
Vector2 guardToTarget = targetPos - guardPos; // vector from our guard to our target

guardFacing.Normalize(); // precompute and store this for optimization
guardToTarget.Normalize();
float dotProduct = Vector2.Dot(guardFacing, guardToTarget);

if (dotProduct > 0)
{
// in front of our guard, so visible
}
else
{
// behind our guard
}



In general, the dotproduct from these normalized vectors can be used as:

-1 = directly behind the guard
0 = left or right from the guard
1 = directly in front of the guard

As the target moves towards where the guardFacing vector is pointing (so it's moving to a point directly in front of the guard), the dotproduct will move to 1. This makes it possible to narrow the field of view, by for example checking if the dotpoduct > 0.25f.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this