# Beginning AI With XNA

## Recommended Posts

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 on other sites
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 on other sites
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 applicableVector2 guardFacing = new Vector2(1, 0); // looking 'right', along the positive x axisVector2 targetPos = new Vector2(-1, 0); // 'behind' the guardVector2 guardToTarget = targetPos - guardPos; // vector from our guard to our targetguardFacing.Normalize(); // precompute and store this for optimizationguardToTarget.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.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628354
• Total Posts
2982230

• 10
• 9
• 11
• 24
• 11