In this Quick Tip you'll learn a technique of conditional enemy movement, based on a classic enemy from an awesome game. Face the ghost and he freezes; look away and he comes for you.
Final Result Preview
Let's take a look at the final result we will be working towards:
Use the left and right arrow keys to move. Walking movement has been simplified for the sake of this Quick Tip.
Step 1: Brief Overview
A player and an enemy will be placed on screen, the player will be controlled using the left and right arrow keys and the enemy will react to the player's position and orientation.
Step 2: Set Up Your Flash File
Launch Flash and create a new Flash Document, set the stage size to 320x200px and the frame rate to 24fps.
Step 3: Interface
This is the interface we'll be using, simple shapes and colors to recreate this behavior.
Convert the characters to Movie Clips and name them ghost and player.
Step 4: ActionScript
Create a new ActionScript Class (Cmd+N), save the file as Main.as and write the following lines, please read the comments in the code to fully understang the class behavior.
package { import flash.display.Sprite; import flash.events.KeyboardEvent; import flash.events.Event; public final class Main extends Sprite { public final function Main():void { addListeners(); } private final function addListeners():void { stage.addEventListener(KeyboardEvent.KEY_DOWN, movePlayer); stage.addEventListener(Event.ENTER_FRAME, follow); } private final function movePlayer(e:KeyboardEvent):void { if(e.keyCode == 37) //move left if left arrow key is pressed { player.x -= 4; player.rotationY = 180; //rotate to match direction } else if(e.keyCode == 39) //move right if right arrow key is pressed { player.x += 4; player.rotationY = 0; //rotate to match direction } } private final function follow(e:Event):void { /* Right side */ if(player.rotationY == 0 && player.x > ghost.x) { ghost.x += 0.4; ghost.y += 0.4; ghost.alpha = 1; ghost.rotationY = 0; } else if(player.rotationY == 180 && player.x > ghost.x) //if the player looks at the ghost { ghost.alpha = 0.5; } /* Left side */ if(player.rotationY == 180 && player.x < ghost.x) { ghost.x -= 0.4; ghost.y += 0.4; ghost.alpha = 1; ghost.rotationY = 180; } else if(player.rotationY == 0 && player.x < ghost.x) //if the player looks at the ghost { ghost.alpha = 0.5; } /* Stop Y if ghost is near floor */ if(ghost.y >= 165) { ghost.y = 165; } } } }
Step 5: Document Class
Add the class name to the Class field in the Publish section of the Properties panel to associate the FLA with the Main document class.
Conclusion
You've learned a simple and useful technique of enemy movement, try it in your own games!
I hope you liked this tutorial, thank you for reading!
Comments