Advertisement

Beginning AI With XNA

Started by April 21, 2008 08:15 PM
1 comment, last by remigius 16 years, 7 months ago
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!
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.
Advertisement
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.
Rim van Wersch [ MDXInfo ] [ XNAInfo ] [ YouTube ] - Do yourself a favor and bookmark this excellent free online D3D/shader book!

This topic is closed to new replies.

Advertisement