Monday, May 7, 2012

Generating Ghosts That Follow in Your Footsteps

Path following is a simple concept to grasp: the object moves from point A to point B to point C, and so on. But what if we want our object to follow the path of the player, like ghosts in racing games? In this tutorial, I’ll show you how to achieve this with waypoints in AS3.


Final Result Preview

Click the SWF, then use the arrow keys to move around. Press space to switch to the ghost, which will follow the path you’ve created.

The Logic Behind Path Following

Let’s suppose the player moves 4 units left and 2 units down from our point of origin. For our ghost to end up in the same location it will have to also move 4 units left and 2 units down from the same point of origin. Now let’s say our player is moving at a speed of 2; for the path following to remain accurate our ghost will also have a speed rate of 2.
What if our player decides to take a pause before continuing on? The obvious solution is for the ghost to keep track of the player’s exact position every tick – but this will involve storing a lot of data. Instead, what we’ll do is simply store data every time the player presses different keys – so if the player moves right for ten seconds, we’ll store the same amount of data as if the player moved right for half a second.
For this technique to work our ghost must abide by the following rules:
  • The ghost and player have the same point of origin.
  • The ghost must follow the exact same path as the player.
  • The ghost should move at the same speed as the player.
  • The ghost has to store the current time each time the player’s motion changes.

Step 1: Setting Up

Start by creating a new Flash file (ActionScript 3.0). Set the width to 480, the height to 320 and frames per second to 30. Leave the background color as white and save the file as CreatingGhosts.fla; lastly set its class to CreatingGhosts.
Before we move into the classes we need to create a pair of MovieClips. Start by drawing two separate 20px squares without a stroke. Convert the first fill to a MovieClip, setting its registration to the center, naming it player and exporting it for ActionScript with the class name Player. Now repeat the same process, except replace the name with ghost and the class with Ghost. Remove these MovieClips from the stage.
Create your document class with the following code:
Read more: Generating Ghosts That Follow in Your Footsteps

No comments:

Post a Comment