Tutorials

February 6, 2009

AS3 Flash Games for Beginners: Character Movement / Handling Multiple Keypresses

More articles by »
Written by: Par
basics1_tn

Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg ThisSubmit to reddit

Movement is extremely important for any game in which you take the role character or object.  Bad movement can completely ruin your game, and good movement can make it feel well polished.  Of course, movement is just one part of your game, but it’s the foundation of everything your character will do, so you need to give it some attention.

This is the second article in the Flash Game Basics series. It picks up where the previous one left off.  The information in this article is not dependent on the previous other than the files being used and the assumption that you can add a Library Object to the stage using AS3.  If you would like to read the previous article first, it can be found here.  If you would like the source code and will just continue along, you can download the source code here.

Step 1: Using KeyObject Class by senocular

When we left off we had added our spaceship to the stage, front and center.  Now we need to make it move.  There are a couple ways we can do this, but the best way to handle keypresses, in my opinion, is found in a class written by an extremely talented programmer, senocular. You can download his class from his website by clicking this link. Just click download source file and save under the same directory as basics1.fla.  (Keep in mind this file is under the package “com.senocular.utils” so you will need to drop it in the utils folder inside senocular which is inside com. Our com folder should now have senocular and asgamer folders inside it.

Okay so we have senocular’s class ready, if you’ve programmed in AS2, you’ll notice senocular’s class gives you the isDown functionality of AS2. So let’s open our Ship class and start setting it up to work with senocular’s class.  We need to import two classes, Senocular’s KeyObject and the Flash Keyboard class. Then we’ll need to create an object of the KeyObject class, which requires the stage to be passed as a parameter.  Problem! we don’t have access to the stage in our Ship class. So we’ll have to pass it from Engine into Ship, No Problem!

Here’s our new Engine Class passing the stage into ourShip.

//our package... simply put, the directory structure to this file
package com.asgamer.basics1
{
	//list of our imports these are classes we need in order to
	//run our application. 
	import flash.display.MovieClip;
	import flash.display.Stage;
 
	//our Engine class it extends MovieClip
	public class Engine extends MovieClip
	{
		//our constructor function. This runs when an object of 
		//the class is created
		public function Engine()
		{
			//create an object of our ship from the Ship class
			var ourShip:Ship = new Ship(stage);
			//add it to the display list
			stage.addChild(ourShip);
 
			ourShip.x = stage.stageWidth / 2;
			ourShip.y = stage.stageHeight / 2;
		}
 
	}
 
}

And here’s our Ship class receiving the stage from Engine, including Keyboard, Stage, and KeyObject classes, and creating an object of the KeyObject class:

package com.asgamer.basics1{
 
	import flash.display.MovieClip;	import flash.display.Stage;
	import com.senocular.utils.KeyObject;
	import flash.ui.Keyboard;
 
	public class Ship extends MovieClip	{
 
		private var stageRef:Stage;
		private var key:KeyObject;
 
		public function Ship(stageRef:Stage)
		{
			this.stageRef = stageRef;
			key = new KeyObject(stageRef);
		}
 
	}
 
}

Okay the Breakdown!

  • Engine class.
    We just added stage into the parameters needed to create an object of the Ship class. We’ll need to add something to the Ship class in order to catch the parameter when it’s sent through, but as far as Engine goes, we’re done with it.
  • Ship class.
    We added three imports… We already discussed two of them, the Stage import was needed because we’re passing the stage through. So we need to know what to do with the stage, therefore, we import the Stage class.
  • Ship class.
    Class variables.
    We added two new class variables. One for the stage reference, stageRef, so we can reuse the stage in other functions in our Ship class.  The other variable is for our KeyObject so we can use it anywhere in the class as well.
  • Ship class.
    Our Constructor Function.
    We take the stageRef variable passed in from Engine and store it in the classes stageRef variable. The this. preceding stageRef tells Flash that it is addressing our class variable and not the one being passed into the function. Then we create our KeyObject and store it in our key variable. KeyObject gets the stage passed into it because we need the stage in order to check for key presses.

Step 2: Enter Frame Listener

Currently our game loads up shows our background and ship and nothing happens :( .  So to make something happen we’re going to write code that will execute everytime flash redraws a frame… in our case 30 times a second.  To do this we need to create an event listener.  So we’ll import a new class add our listener and create a new function. Here’s the new Ship class code.

package com.asgamer.basics1{
 
	import flash.display.MovieClip;
	import flash.display.Stage;
	import com.senocular.utils.KeyObject;
	import flash.ui.Keyboard;
	import flash.events.Event;
 
	public class Ship extends MovieClip	{
 
		private var stageRef:Stage;
		private var key:KeyObject;
 
		public function Ship(stageRef:Stage)
		{
			this.stageRef = stageRef;
			key = new KeyObject(stageRef);
 
			addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
		}
 
		public function loop(e:Event) : void
		{
			y--;
		}
 
	}
 
}

The Breakdown!

  • We import flash.events.Event, because we are listening for an event now.
  • addEventListener(Event.ENTER_FRAME, loop, false, 0, true); Okay so our Ship is calling the addEventListener function. We need to pass the first two parameters: what kind of event we need and what function to call each time the event occurs.  The last three parameters are optional but setting the last one to true turns on weak referencing which is recommended. For more information read about it at Grant Skinner’s blog here.
  • public function loop(e:Event) : void. Our enter frame function. An event parameter is being passed to it, all event listeners pass an event parameter into the function they call, so be prepared to catch it. The : void just let’s Flash know this function returns nothing.
  • y–; Each time we enter frame, we move up 1 pixel. y– is the same as writing y-=1 or y = y -1.  Remember the equals sign is not equals in an algebraic sense, it more literally means store as.

Compile the game (CTRL+ENTER) and watch your ship fly off screen.

Step 3: Reading Key Presses.

Alright, let’s start reading when you press a key.  Delete the y– line.  And on with the if statements.

package com.asgamer.basics1{
 
	import flash.display.MovieClip;
	import flash.display.Stage;
	import com.senocular.utils.KeyObject;
	import flash.ui.Keyboard;
	import flash.events.Event;
 
	public class Ship extends MovieClip	{
 
		private var stageRef:Stage;
		private var key:KeyObject;
 
		public function Ship(stageRef:Stage)
		{
			this.stageRef = stageRef;
			key = new KeyObject(stageRef);
 
			addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
		}
 
		public function loop(e:Event) : void
		{
			if (key.isDown(Keyboard.LEFT))
				x -= 2;
			else if (key.isDown(Keyboard.RIGHT))
				x += 2;
 
			if (key.isDown(Keyboard.UP))
				y -= 2;
			else if (key.isDown(Keyboard.DOWN))
				y += 2;
		}
 
	}
 
}

Let’s break this down.

  • We added two if else if statements. One to read our horizontal changes, the other to read our vertical changes.  So if the LEFT keyboard key is down we want to move x left 2 pixels. If the RIGHT key is down move right 2 pixels. The same goes for vertical movement.

Compile this thing. Test it out.

Here’s the final source code for this step:
AS Gamer – Flash Games for Beginners Part 2 Source

Awesome in the next tutorial, we’ll dive deeper into Movement Dynamics and do some easy tricks to make our ship animate in a slick 3D like manner.

Click here to see the next tutorial.

Similar Posts:


Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg ThisSubmit to reddit


About the Author

Par
Hey! Don't be surprised, I'm a flash developer. While Flash is definitely one of my favorite languages to develop in, most of all I just like making games. If you want to see the games I've developed so far head over to my website, DigitallyBold, in the link below. If you want to know more about what I'm working on now and in the future be sure to follow me on twitter.




51 Comments


 
 

  1. Michael

    First and foremost thank you for a great tutorial. the time and effort you took to explain things are amazing . thank you personally. I would like to also add that i changed the package name from what it was before to com.asgamer.basics1.keyObject because it wouldn’t work without it. If anyone else had the same problem try changing it and maybe it would work.

    I graduated with a BA in CS but i forgot all my programming skills.
    Can someone explain ( this. ) better because i never got that concept.

    Thanks again guys.


 
 



Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">


Advertisement