Tutorials

February 22, 2009

AS3 Character Movement: Helicopter Games

thumbnail1

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

There are tons of games that involve character movement and controls and because one of the most popular tutorials on AS Gamer at the moment is about movement… I figured it was time to discuss a variety of movement methods. The first one we are going to discuss is Helicopter game movement. Everybody has played those helicopter games where you have to fly the helicopter through a maze without crashing. If you haven’t well then I suggest you try out Skylocopter 2 and Helicopter Game. Anyway, today we’re going to learn how to make that helicopter move the way it does.

You are reading AS3 Character Movement Read more from this series of articles.

First thing you are going to need is the zip archive.

Download the AS3 Character Movement: Helicopter Games ZIP Archive

It’s simply the fla and the as files we are going to use to create our game.  Once extracted you will notice the helicopter.fla and the com folder. Inside the com folder is an asgamer/helicopter folder that has our document class, Engine, and our Helicopter’s class, Helicopter.  There is also a senocular folder that has his KeyObject class in it. It’s a great class that we will be using to control our keyboard presses for our game.

Step 1: Getting Started

Okay so open up helicopter.fla, Helicopter.as, and Engine.as in Flash.  If you look at the fla file you’ll notice in the Library (CTRL+L) we have three movieclips.  Background is the sky, that you see on the stage. Blade is the rotating blade at the top of our helicopter and last we have a movieclip of our helicopter altogether.  The Helicopter movieclip is linked to the Helicopter class in our helicopter.as file.  You’ll also notice our document class is pointing to the Engine class in our Engine.as file (If you don’t understand document class and linkage you need to read my AS3 Flash Games for Beginners tutorial to familiarize yourself with the basics.)

Here’s what our Engine.as should look like:

package com.asgamer.helicopter
{
 
	import flash.display.MovieClip;
 
	public class Engine extends MovieClip
	{
 
		public function Engine() : void
		{
			var heli:Helicopter = new Helicopter();
			addChild(heli);
		}
 
	}
 
}

Very simple document class. We just create an instance of Helicopter and add it to the stage…. We need to do one thing first though. we need to pass the stage into our Helicopter class so we can use our keyboard to control our helicopter through the Helicopter class. So just var heli:Helicopter = new Helicopter(); to var heli:Helicopter = new Helicopter(stage);.

Now here’s our Helicopter class:

package com.asgamer.helicopter
{
 
	import flash.display.MovieClip;
 
	public class Helicopter extends MovieClip
	{
 
	}
 
}

Even simpler. But now we need to catch our stage reference that is passed through from Engine. So let’s add our constructor function… catch the stage being passed in a class variable called stageRef and make sure to import flash.display.Stage. If you understand what I am talking about try to do this yourself… if not here’s what your class should look like now.

package com.asgamer.helicopter
{
 
	import flash.display.MovieClip;
	import flash.display.Stage;
 
	public class Helicopter extends MovieClip
	{
 
		private var stageRef:Stage;
 
		public function Helicopter(stageRef:Stage) : void
		{
			this.stageRef = stageRef;
		}
 
	}
 
}

Makes good sense right? If not you definitely need to read AS3 Flash Games for Beginners tutorial.

Step 2: What do we want our Helicopter to do?

Okay so what kind of movement do we want our helicopter to have?  When we press an arrow key it moves in the direction of the arrow key. Gravity will constantly be pulling our helicopter down so we will have to press up often to keep it in air.  Left and right will move our helicopter in those directions and flip him around so it points in the directions we want it to face.  Also we want it to speed up gradually in whatever direction it is going and cap at a certain speed. And finally we want it to slow down when no keys are being pressed to move it in a certain direction.

Wow that’s a lot of details… let’s think about all the variables it’s going to take to make this work.  We know we have x and y which controls our helicopter’s postion.  But what other ones will we need?

  • gravity. a number so we can pull our ship downward every frame
  • vy and vx. This is the velocity of our ship in the x and y directions… so we can speed up and slow down our helicopter.
  • maxspeedG and maxspeed.  I created two maxspeeds because I want our helicopter to be able to fall faster than in can fly up and horizontal.  the falling maxspeed is maxspeedG… the G representing gravity.
  • friction.  a number unlike real friction but having a friction like effect. We’ll use our friction variable to slow our ship down in x when no keyboard keys are being pressed.
  • key. This will be our object of the keyObject class.  We’ll use it to determine if any keys are being held and what to do if so.

Alright so let’s add these to our helicopter class.

package com.asgamer.helicopter
{
 
	import flash.display.MovieClip;
	import flash.display.Stage;
 
	public class Helicopter extends MovieClip
	{
 
		private var gravity:Number = .4;
		private var vy:Number = 0;
		private var vx:Number = 0;
		private var key:KeyObject;
		private var stageRef:Stage;
 
		private var maxspeedG:Number = 9;
		private var maxspeed:Number = 6;
		private var friction:Number = .92;
 
		private var stageRef:Stage;
 
		public function Helicopter(stageRef:Stage) : void
		{
			this.stageRef = stageRef;
			key = new KeyObject(stageRef);
		}
 
	}
 
}

The breakdown of these is simple. We just added all the variables we discussed above as private class variables.  There initial values are simply values that I feel will work great for our helicopter… we’ll discuss them more as we put them to use later.

We also added the key = new KeyObject(stageRef) line to our constructor function.  This just creates a new object of KeyObject and assigns it to key. Now we can check for keypresses :)

Step 3: Making our Helicopter Move

Okay so before we make our helicopter move we have to take care of a couple things. First of all we’re missing 3 imports that we must have.  So go up to your imports and import these 3 classes.

  • import flash.events.Event; //so we can use events and  listeners
  • import com.senocular.utils.KeyObject; //senocular’s keyobject class
  • import flash.ui.Keyboard; //the keyboard class so we know what keys to map.

Perfect. Now we need to add an on enter frame event listener to our helicopter and place our helicopter dead center when our game loads.  So we add the event listener and center our helicopter and our class looks like this.

package com.asgamer.helicopter
{
 
	import flash.display.MovieClip;
	import flash.events.Event;
	import com.senocular.utils.KeyObject;
	import flash.display.Stage;
	import flash.ui.Keyboard;
 
	public class Helicopter extends MovieClip
	{
 
		private var gravity:Number = .4;
		private var vy:Number = 0;
		private var vx:Number = 0;
		private var key:KeyObject;
		private var stageRef:Stage;
 
		private var maxspeedG:Number = 9;
		private var maxspeed:Number = 6;
 
		private var friction:Number = .92;
 
		public function Helicopter (stageRef:Stage) : void
		{
			this.stageRef =stageRef;
			key = new KeyObject(stageRef);
 
			addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
 
			x = stageRef.stageWidth/2;
			y = stageRef.stageHeight/2;
 
		}
	}
}

Nothing too drastically new here.  we use addEventListener to setup our AS2 equivalent of onEnterFrame.  So now every time we enter a frame our class is calling loop(which we need to hurry and create).  We set our x to half the stage’s width and our y to half of the stages height. Which logically should be dead center.  So let’s create that loop function. I’ll write out all the code then we’ll break it down line by line.

package com.asgamer.helicopter
{
 
	import flash.display.MovieClip;
	import flash.events.Event;
	import com.senocular.utils.KeyObject;
	import flash.display.Stage;
	import flash.ui.Keyboard;
 
	public class Helicopter extends MovieClip
	{
 
		private var gravity:Number = .4;
		private var vy:Number = 0;
		private var vx:Number = 0;
		private var key:KeyObject;
		private var stageRef:Stage;
 
		private var maxspeedG:Number = 9;
		private var maxspeed:Number = 6;
 
		private var friction:Number = .92;
 
		public function Helicopter (stageRef:Stage) : void
		{
			this.stageRef =stageRef;
			addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
			key = new KeyObject(stageRef);
 
			x = stageRef.stageWidth/2;
			y = stageRef.stageHeight/2;
 
		}
 
		public function loop(e:Event) : void
		{
			vy += gravity;
			y += vy;
			x += vx;
 
			if (vy > maxspeedG)
				vy = maxspeedG;
			else if (vy < -maxspeed)
				vy = -maxspeed;
 
			if (vx > maxspeed)
				vx = maxspeed;
			else if (vx < -maxspeed)
				vx = -maxspeed;
 
			if (vx > 0)
				scaleX = 1;
			else if (vx < 0)
				scaleX = -1;
 
			if (y > stageRef.stageHeight)
			{
				y = stageRef.stageHeight;
				vy = 0;
			}
 
			rotation = vx*2;
 
			if (key.isDown(Keyboard.RIGHT))
				vx += .5;
			else if (key.isDown(Keyboard.LEFT))
				vx -= .5;
			else
				vx *= friction;
 
			if (key.isDown(Keyboard.UP))
				vy -= 1;
			else if (key.isDown(Keyboard.DOWN))
				vy += .5;
 
		}
 
	}
 
}

Okay the breakdown:

  • vy += gravity; Very simple… on every enter frame we want gravity to pull our helicopter down. So we add gravity to our helicopter’s vertical velocity.
  • y += vy; x += vx; Add the velocity of our helicopter to our helicopter’s position.
  • if (vy > maxspeedG) If our helicopter’s speed is greater than the maxspeedG then we set it back to maxspeedG.  You’ll notice vy < maxspeed is used instead of maxspeedG. This is because we only want our maxspeedG to be applied to our helicopter when it is falling.  The rest of the time we want to use maxspeed. We use the same logic for vx as we do vy.
  • if (vx > 0) scaleX = 1; If our velocity is greater than zero then we are moving right so scaleX our ship to 1. Which is it’s default scale. If our helicopter’s vx is less than zero we must be moving left so change the scaleX to -1. Which is the same as flipping it’s direction.
  • if (y > stageRef.stageHeight) If our helicopter has fell off the stage then we set it back to the bottom of the stage and set it’s y velocity to 0.  We could set it to -2 or so if we wanted it to bounce.  Give it a try later.
  • rotation = vx*2; So when our helicopter is moving fast we want it to tilt in the direction it is going. Making the rotation do this will create the desired effect.
  • if (key.isDown(Keyboard.RIGHT)) Using senocular’s class we can check if a key is down.  So here we check if the right arrow key is down… if so we add to our vx. We do the same the left arrow key is being pressed.  If neither are being pressed we add friction.  Since our friction is less than one (and greater than zero) if we multiple it by any number that number will get smaller. Continually doing this will make the number get closer and closer to 0 which makes our helicopter slow down.  Simple huh?

Alright… we just created movement for our helicopter character! Here’s the final swf, now go use this in your next game.

And here’s the final source code:
AS3 Character Movement: Helicopter Games

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.




20 Comments


  1. Bret

    This is great tut…..however I have been banging my head on the desk all day trying to figure out why I can’t see a helicopter! I don’t get any compiler errors or anything when I test. just no helicopter.

    Any ideas?

    Thanks again for all your awesome tuts!


  2. Bret

    woops……….didn’t see the link to the finished product….got that and it works like a charm…but for some reason I can’t get the code above to display a helicopter. no errors though so I am not sure what I am doing wrong. I don’t even see any differences in the finished code either. Oh well…

    Again great tutorial………great site too!


  3. Hernan

    Not sure about speed (but it cant hurt too much right?), but I usually replace this:

    if (vy > maxspeedG)
    vy = maxspeedG;
    else if (vy < -maxspeed)
    vy = -maxspeed;

    With this:

    vy = Math.min (maxspeedG, Math.max (-maxspeed, vy));


  4. Par

    @Hernan
    Yep, that works great. I’d never thought of doing it that way. Thanks for sharing your method of limiting a number between two values. It’s a little less obvious than a simple conditional (when reading the code) but I like it. :)


  5. Chris

    Hello, Great tut however i think everyone would benifet if you showed us how to include checks for other button presses, ie most games that require movement have optional buttons, the way you have used Up, Down ect and aslo the ‘wasd’ keys. How can you allow both to be used with this code?

    Many Thanks
    Chris


  6. Par

    There’s an OR command for conditionals use it.


  7. Alex

    I think I love you. You just explained like a million things. AS3 motion was always awkward for me. THANKS A WHOLE BUNCH :D


  8. Alex

    Okay, I just have one question. That stageRef variable is a little confusing.

    In the third and fourth code box it says function instead of var, that threw me off at first. Then with it fixed I got a 1046 error in line 18. Said “Type was not found or was not a compile-time constant: Stage”

    The class name is not Ship in the fla (which would cause it)

    Any ideas?


  9. In the third and fourth code box it says function instead of var,

    @Alex >

    it should be var instead of function …. i am still reading it..


  10. Topi

    lil question,
    how is vy and vx affecting the position of the heli?
    they are simple private variables of type number.
    if it were written somewhere in the code heli.x = vx or something like that it would have been simpler for me to understand. right now i am confused :0


  11. Leo

    Topi, I’m not an expert at all, but it would make sense to see that those variables are private to the Helicopter class. In essence, the variables are effecting the Helicopter the same way heli.x would, except without the heli part. Much cleaner this way IMO


  12. Sam

    I dont get the helicopter to come up on the screen


  13. FTwo

    @Bret (If you read this)
    Have you made sure that the helicopter symbol has the correct linkage?


  14. Zatarra

    Some extra features I had fun putting in: landing gear disappears when you’re airborne; blades stop spinning when your’e grounded.

    //if grounded
    if(y >= stageRef.stageHeight)
    {
    y = stageRef.stageHeight;
    vY = 0;
    rotation = 0;
    this.wheels.alpha = 1;
    this.propellor.stop();
    this.blade.stop();
    }
    //if airborne
    else
    {
    vY += gravity;
    rotation = 2 * vX;
    this.wheels.alpha = 0;
    this.propellor.play();
    this.blade.play();
    }


  15. RECK

    Ok so how do I make it so I follow the helicoper when I go out of the frame?


  16. Branden

    Argument count mismatch on com.hg.eng::Helicopter(). Expected 1, got 0.

    i get this when i try to launch the swf


  17. joe

    hey I have been trying simply add a separate object form the library on the stage would I have to write a separate as3 file or can I add it to an existing constructor code. If so where would this be within the files?


  18. Suzie

    Hi there, was wondering if someone could show me how to replace the AS2 code used in the KeyObject Class with something similar in AS3?

    Great tutorials, many thanks!


  19. Jayms

    Is there any way to make something like this all within one FLV document? Having all these links and folders and separate as files is really confusing.



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