| XNA Platformer Starter Kit - Field of View for Enemies |
| Written by Jeff Brown |
Field of View for EnemiesHere's a video showing off the final product: Please note, the texture is being drawn just to show how/when/where his field of view is. You'd probably take the code out for drawing the spotlight rectangle unless it's part of your design!
For the image above, Right Click>Save As and save it to “HighResolutionContent>Overlays” folder (or wherever you see fit, just remember the location for the LoadContent call) Remember to load it into the project solution by navigating to “HighResolutionContent>Overlays” and right click on the Overlays folder and Add>ExistingItem>spotlight2.png.
Add these underneath after public Rectangle BoundingRectangle{...} public Rectangle SpotlightRectangle { get { int left = (int)Math.Round (Position.X - sprite.Origin.X) + localBounds.X; int top = (int)Math.Round (Position.Y - sprite.Origin.Y) + localBounds.Y; if((int)direction == 1) return new Rectangle( left + localBounds.Width, top, spotlightTexture.Width, (spotlightTexture.Height / 2)); else return new Rectangle( left - spotlightTexture.Width, top, spotlightTexture.Width, (spotlightTexture.Height / 2)); } } public bool iSeeYou; Texture2D spotlightTexture; Next add the following line in LoadContent method at the bottom: spotlightTexture = Level.Content.Load<Texture2D>("Overlays/spotlight2");
Now in the Update method add the following at the top: if(SpotlightRectangle.Intersects(Level.Player.BoundingRectangle)) iSeeYou = true; else iSeeYou = false; In the Draw method add the following to the bottom: if (iSeeYou) spriteBatch.Draw(spotlightTexture, SpotlightRectangle, null, Color.Red); else spriteBatch.Draw(spotlightTexture, SpotlightRectangle, null, Color.White);
Now I’m sure you’ve noticed a few flaws, like Hey, he can see me through walls! or Hey, his field of view is a rectangle… At this point you might want to add clipping (so obstacles block the enemy’s field of view) or change the field of view to something more realistic. The solution to these problems will involve using some math skills you were saving for something like this! I found this to be the quickest solution to test a field of view for enemies. Eventually I’ll make it more complex but this works fine for the near future. |
