Wednesday, December 28, 2011

Use Vector Regions to Implement Field of View in a Flash Game

In this tutorial, you will learn how to cast a field of view of a turret guarding a specific location. When an enemy is within the turret's field of view, the turret will shoot at them. Vector math will be used to help in implementing this field of view.


Final Result Preview

Let's take a look at the final result we will be working towards. Click on the turret at the bottom of stage to begin the simulation.


Step 1: Field of View

I’m sure most readers have used cameras. Every camera has a view angle, defined by the type of lens attached. There are narrow and wide view angles. View angles constrain the field of view into a sector. From a top-down position, they look like the diagram below. If you take a picture, eveything within the grayed area will be captured.

Field of view: narrow and wide

The turret's field of view in our simulation is like that of a camera. If there's an enemy within its field of view, a guard will respond (sound an alarm, take aim, shoot, etc).


Step 2: Basic Concept

Mathematical conditions to determine item within FOV

The diagram above shows the field of view of turret. Usually the angle of view will be equal on both the left and the right. The radius will also be consistent throughout the sector. So to check whether an enemy is within a turret's field of view, these two mathematical conditions can be used:

  1. Distance between turret and enemy is less than radius.
  2. Angle from turret's line of sight to enemy is less than 30°.

Step 3: Define Field of View Using Vector

We shall use vector math to help us. In this case, the vectors in consideration are vLine2 and vLine3. We can:

  • Compare magnitudes of vLine2 and vLine3 to validate Condition 1 from Step 2.
  • Compare angle sandwiched between vLine2 and vLine3 to validate Condition 2 from Step 2.
Read more: Use Vector Regions to Implement Field of View in a Flash Game

No comments:

Post a Comment