Tracking Missile in Box2D

If you have been playing around with Box2D then chances are you have already figured out how to simulate linear projectile motion or maybe even tried to simulate arrow flight. These are all great places to start, but maybe you are looking for something more advanced? How about a projectile that scans for targets and when it has locked on to one follows it to the bitter end?

Try the demo below. Place your mouse cursor in the canvas object. The target will fix itself to the mouse cursor indicating the target. Press the mouse button to release missiles. The missiles will lock onto the target and follow the target. Try to dodge the missile by moving your cursor around. The missiles will explode if they hit the target or when they run out of gas. The explosion FX are HTML5 based, something that was covered in a previous post.

Here’s how the demo works:

  1. Setup a contact listener to detect when a missile hits the target. The basics with the contact listener in Box2D is covered in this post. This example uses the PostSolve contact listener event.
  2. Setup event listeners to detect when the mouse was moved or clicked.
  3. Create the target. The target is a dynamic Box2D body that is moved around by the mouse and is what the missiles will try to detect and target.
  4. Create a missile class that is able to scan for targets, lock on to targets, and follow targets as they move.

This is what it looks like when setting up the PostSolve contact listener:

The event listeners needed to capture mouse movement and mouse clicks look like this:

The target has a very basic definition and is created when initialising the demo. The code looks like this:

The only thing to consider is that the target has user data that is used during collisions to determine whether the missile collided with the target.

The last component is the missile class. Below are the most important components of the missile class. Check out the source code to get the full class definition from the link below. The broad strokes are as follows:

  • The update function checks if the missile has locked-on to a target. If the missile has acquired a target then the attribute tracking_sensitivity is used to determine when to change the course of the missile. The attribute turn_force controls how fast the missile turns.
  • If a target is not acquired, then the missile will scan for a target using the ray cast method. The parameter radarWidth is used to define how wide the scanning area is, whereas radarRadius defines length of the rays, e.g. how far the missile can detect a target. If multiple targets are found, then the closest target is selected as the target for the missile. This is where you could define other selection criteria, e.g. randomised, value-based, etc.

Download the code:  missile.js (300 downloads)