Sidescrolling Platformer ~Part 2~ Scrolling the Background with the Arrow Keys

After setting up the basic outline of the platformer in Part 1, we will create a scrolling effect for the background in this tutorial which will be controlled by the arrow keys.

Keyboard Controls

One of the most useful things to be able to do with AS3 is to use the keyboard to control the game. It requires a bit of code, but once you learn to do it you will have a very important building block for any game.

Start out by adding the following code to the Actions panel on frame 1 of the timeline:


stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);

Both of these lines add event listeners to the stage. The first one will run the “keyDownHandler” function every time any keyboard key is pressed. And the second one will run the “keyUpHandler” function every time you release one of those keys.

One problem… those functions don’t exist yet. So let’s add them underneath the listeners:


function keyDownHandler(e:KeyboardEvent):void{

}

function keyUpHandler(e:KeyboardEvent):void{

}

Right now we only have the shell of each function — they don’t contain the actual code we need to run yet. If you’re still new to event listeners, make special note of the parameter of the function: (e:KeyboardEvent). The letter e doesn’t really mean anything beyond just being an abbreviation of “event” (you could use any word or letter in that spot as long as you use that same word throughout your program). However, we are assigning it to hold all of the information of the KeyboardEvent which triggered this function, so we can use e to figure out which key was pressed.

Time to add the real code of the functions. Don’t be intimidated… it looks like a lot but really it is just repeating itself.


function keyDownHandler(e:KeyboardEvent):void{
if(e.keyCode == Keyboard.LEFT){
trace("left pressed");

} else if(e.keyCode == Keyboard.RIGHT){
trace("right pressed");

} else if(e.keyCode == Keyboard.UP){
trace("up pressed");

} else if(e.keyCode == Keyboard.DOWN){
trace("down pressed");
}
}

function keyUpHandler(e:KeyboardEvent):void{
if(e.keyCode == Keyboard.LEFT){
trace("left released");

} else if(e.keyCode == Keyboard.RIGHT){
trace("right released");

} else if(e.keyCode == Keyboard.UP){
trace("up released");

} else if(e.keyCode == Keyboard.DOWN){
trace("down released");
}
}

This code will trace to the output panel whenever you press or release the up, down, left, or right arrow keys. Run your program and try pressing and releasing each of the arrow keys.

Each function is made up of 4 repetitions of this basic code-block: if(e.keyCode == Keyboard.LEFT)

This accesses the information stored in our local variable e, and checks what its keyCode is. Each key on your keyboard has a different keyCode assigned to it. The arrow keys’ keyCodes are simply their direction in capital letters, but most keys use a number assigned to them instead (just google “AS3 Keycodes” and you can easily find a chart of them all).

Right now the only thing that happens is a trace statement. How do we change this into scrolling the background? Before we can change the code in these functions we will need to add a few more lines at the top of our code file:


var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
var upPressed:Boolean = false;
var downPressed:Boolean = false;

var xScrollSpeed:int = 10;
var yScrollSpeed:int = 10;

The x and y scroll speeds are just constant numbers which will determine how fast the background moves when it is scrolling.

The Boolean variables will be used to tell whether or not a key is pressed. If it is currently held down, the respective variable will equal true. Otherwise, it will equal false.

Now go back to the keyHandler functions and replace each trace statement with code to update these new variables:


function keyDownHandler(e:KeyboardEvent):void{
if(e.keyCode == Keyboard.LEFT){
leftPressed = true;

} else if(e.keyCode == Keyboard.RIGHT){
rightPressed = true;

} else if(e.keyCode == Keyboard.UP){
upPressed = true;

} else if(e.keyCode == Keyboard.DOWN){
downPressed = true;
}
}

function keyUpHandler(e:KeyboardEvent):void{
if(e.keyCode == Keyboard.LEFT){
leftPressed = false;

} else if(e.keyCode == Keyboard.RIGHT){
rightPressed = false;

} else if(e.keyCode == Keyboard.UP){
upPressed = false;

} else if(e.keyCode == Keyboard.DOWN){
downPressed = false;
}
}

You will no longer see a trace statement when you press the arrow keys, nor will you see any other visual indication that your game is working. But behind the scenes, your program now knows which keys are being pressed, which is essential to making our game.

Scrolling the Background

Before we can make the background scroll, we need to give it an instance name. Click on the background you had drawn from Part 1 and name it background. Now we can refer to the background MovieClip object through our code.

Back in the Actions panel add another Event Listener, one that creates the main game loop. If you’ve gone through the Pong tutorials this should look familiar:


stage.addEventListener(Event.ENTER_FRAME, loop);

function loop(e:Event):void{

}

Slow me down if I’m going too fast, but I’m assuming you all know how this code works.

This will run 30 times every second, giving a pretty smooth animation to anything we update inside the function. It’s finally time to make our game do something visual! Inside the loop function, update the position of the background depending on which key-Pressed variables are true:


function loop(e:Event):void{

	if(leftPressed){
		background.x += xScrollSpeed;

	} else if(rightPressed){
		background.x -= xScrollSpeed;

	}

	if(upPressed){
		background.y += yScrollSpeed;

	} else if(downPressed){
		background.y -= yScrollSpeed;

	}
}

Test your game and marvel at the magical effect! Or just test mine below: (click on the game to select it, then use the arrow keys to “move the player” around the background)

That’s as far as we are going in this tutorial part. Right now it obviously looks like fake movement, because the player is completely static. In the next tutorial we are going to program the most significant part of the game: making the player react to the background in a realistic way. If you want to be notified as new tutorials are posted, make sure to subscribe.

I’ve already committed to adding an extra tutorial about enemy AI at the end of the series just because someone requested it in the comments. Honestly, if you have any requests of something you would like to learn to add to the game, just ask! Leave a comment below, or drop me an email at AS3GameTuts@gmail.com.

As always, feel free to download the source code on your way out!

65 comments on “Sidescrolling Platformer ~Part 2~ Scrolling the Background with the Arrow Keys

  1. Michael says:

    Awesome tutorial as always!! Can’t wait for the next part! Thanks again for helping all of us new to AS3 learn!

  2. wizrares says:

    that’s awesome, but what do you do if you have actual platforms? Just put the platforms as part of the background and then do the collision with the elements of the background?

    • Ben Reynolds says:

      Yeah, you’ve pretty much got it right, at least for this method of making a sidescroller (there are a bunch of different possible ways). I’ll answer this fully in the next tutorial, but basically what I did in my old game was to nest multiple layers of movieclip objects inside the scrolling background. So for example inside the “background” object there is a movieclip named something like “collide” which contains all of the objects for the player to check for collisions with. And inside that object you can put any type of object you want, such as a platform.

  3. Michael says:

    Part 3! Part 3! Part 3! Lol. Just joking. But I am looking forward to it.

  4. Michael says:

    What’s the ETA on part 3? Lol. Just excited to move my game a long that’s all. Haha. Happy New Year by the way!!!

    • Ben Reynolds says:

      Happy New Year! Sorry for the long wait, I had a busy December and decided to hold off from writing during the holidays. The tutorial is pretty close to completion… If I have time in the next couple days I’ll try to post it by the end of tomorrow. Otherwise I’ll be sure to get it done by the end of the week :-)

    • Ben Reynolds says:

      Part 3 is now up and running! :)

  5. Kemik says:

    It would be cool to add a timer, like in Super Mario Bros. You know, the one that counts down from 400? ;) (I guess that would be similar to making the score keeper in Pong?)

    Your tutorials rock, by the way. :D

  6. Sketchist says:

    Just letting you know it is a great tutorial and it seems to work all right, but… in reall games the background doesn’t move like you depict. The character walks and they make something called a vCam to follow the character wherever it goes but to keep the char in the center of the screen…

  7. kevin allen says:

    very, very well done. Your ability to put these tutes together and make them SO easy to follow is really amazing considering how difficult some other are to follow.

    Thanks very much for all your effort. I’m using your tutorials as the basis for a university project. I will of course site you and your efforts here :)

  8. Steven says:

    Your example videos aren’t showing up :(

  9. beckaboom says:

    dude you are so awesome! it’s impossible to find scripts in action script 3 about making a sidescroller. Not only do you give the script for free, but you include the source material too thanks man :}

  10. Oskil says:

    heloo ;)
    i need tutorial scroling background like this game_ http://www.youtube.com/watch?v=dsVIvUpRJbo

    you can help me? please

  11. 3dgold says:

    Hey after the first part of the script when its supposed to trace my buttons to the screen I get these compiler errors. Any help would be appreciated.

    • 3dgold says:

      Sorry forgot to post the errors here they are
      Scene 1, Layer ‘Actions’, Frame 1, Line 6 1119: Access of possibly undefined property Keycode through a reference with static type flash.events:KeyboardEvent.

      Its the same for every line that uses the if(e.Keycode == Keyboard.LEFT) or right, up, or down.

      Thanks for any help.

      • Ben Reynolds says:

        I haven’t tested your code myself, but I am pretty sure your error is in your capitalization of “Keycode”. I think it should be “keyCode” instead. It’s a tiny difference, but capitalization counts.

  12. edison says:

    thanks for this tutorials.. saludos desde colombia…

  13. FlashGamer says:

    Theres a problem i cant seem to fix… the first big chunk of code that you give (where you say dont be intimidated, looks like alot but its just repeating) gives me an error: it says you duplicated the function, but i copied and pasted it so idk if changing the funcion name will do anything unexpected for me.

    PS im new to flash, just started abt a month ago

  14. Jeremie Picaso says:

    hello guys im new here and i have created an as3 game side-scroller but i’m stock w/ just jumping and hopping around my game without an attack.. can you add Mr.Ben Reynolds an sword attack here in your tutorials?

  15. Carl says:

    I can’t move the game :( help for our thesis tomorrow :'(

  16. thisguycm says:

    I can\’t move the game :( help for our thesis tomorrow :’( reply asap sir..

  17. thisguycm says:

    and btw, sir can you teach me how to link flash to a database? thank you so much in advance. :)

  18. nik says:

    short question…is var and event listeners position in the code kinda important or very important, as I can’t get pong or this game to work properly…if so, can you make a tutorial about this?

    • Ben Reynolds says:

      Variable definitions can be anywhere in the code. I usually put them up at the top, just to stay organized. As for eventListeners, it depends, but for the most part just put them in somewhere where they will be called once, usually near the beginning of where your code begins to execute.

  19. legice says:

    I would just like to ask, if var and event listener placement is important or very important, as my characted does nothing?

  20. Swyrl says:

    tutorial is much appreciated, and I am planning to move from game-maker to flash. This tutorial series is not only helping me in this endeavor, but also helping me build a flash platformer that I’ve wanted to make for some time now.
    Unfortunately, I seem to be having a problem with variables:
    it says that the .x and .y of the background is undefined, and because of this, it doesn’t do anything. Any ideas of how to fix this? (I’m using AS3 from the latest version of flash)
    Thanks! -Swyrl

  21. Zim_of_rite says:

    I love your tutorials! I’ve wanted to make games for a LONG time now, and you’re really helping me get it!

  22. Nate says:

    Thanks for the tutorials, pretty simple to follow. I am getting an error when I complete the coding on this page and run the test movie. The error is:
    “Access of undefined property background”, in each of the lines that contain a background.x, background.y or xScrollSpeed or yScrollSpeed. Any help?? I am a n00b. Thx.

  23. Ema says:

    Hey, Thanks for posting these tutorials, I’ve learned a lot about basic programming. I’m having a problem with the scrolling background though. The variables all work fine and the background scrolls when I press the respective key, but the background won’t stop scrolling when I release the key, so my character just floats continuously off the background into space. I feel like I might’ve misnamed one of the key events, but I’m not quite sure how to fix it. Thanks!

    • Ema says:

      Nevermind! I actually ended up repeating a function code twice in the keyboard events, so it works great now. Thanks again for these tuorials!

  24. raymond says:

    hi ben i done it in as file again here the code
    package {

    import flash.display.MovieClip;
    import flash.events.KeyboardEvent;

    public class Platform extends MovieClip {

    public function Platform() {
    stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
    stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);

    }
    function keyDownHandler(e:KeyboardEvent):void{
    if(e.keyCode == Keyboard.LEFT){
    trace(“left pressed”);
    } else if(e.keyCode == Keyboard.RIGHT){
    trace(“right pressed”);
    } else if(e.keyCode == Keyboard.UP){
    trace(“up pressed”);
    } else if(e.keyCode == Keyboard.DOWN){
    trace(“down pressed”);
    }
    }
    function keyUpHandler(e:KeyboardEvent):void{
    if(e.keyCode == Keyboard.LEFT){
    trace(“left released”);
    } else if(e.keyCode == Keyboard.RIGHT){
    trace(“right released”);
    } else if(e.keyCode == Keyboard.UP){
    trace(“up released”);
    } else if(e.keyCode == Keyboard.DOWN){
    trace(“down released”);
    }
    }
    var leftPressed:Boolean = false;
    var rightPressed:Boolean = false;
    var upPressed:Boolean = false;
    var downPressed:Boolean = false;

    var xScrollSpeed:int = 10;
    var yScrollSpeed:int = 10;

    function keyDownHandler(e:KeyboardEvent):void{
    if(e.keyCode == Keyboard.LEFT){
    leftPressed = true;
    } else if(e.keyCode == Keyboard.RIGHT){
    rightPressed = true;
    } else if(e.keyCode == Keyboard.UP){
    upPressed = true;
    } else if(e.keyCode == Keyboard.DOWN){
    downPressed = true;
    }
    }
    function keyUpHandler(e:KeyboardEvent):void{
    if(e.keyCode == Keyboard.LEFT){
    leftPressed = false;
    } else if(e.keyCode == Keyboard.RIGHT){
    rightPressed = false;
    } else if(e.keyCode == Keyboard.UP){
    upPressed = false;
    } else if(e.keyCode == Keyboard.DOWN){
    downPressed = false;
    }
    }

    stage.addEventListener(Event.ENTER_FRAME, loop);

    function loop(e:Event):void{
    if(leftPressed){
    background.x += xScrollSpeed;
    } else if(rightPressed){
    background.x -= xScrollSpeed;
    }
    if(upPressed){
    background.y += yScrollSpeed;
    } else if(downPressed){
    background.y -= yScrollSpeed;
    }
    }
    }
    }

    error : 1021 duplicate function definition

    • nerfherder17 says:

      This is waaaay late, but in case nobody replied to you, you have two keyUpHandler functions and two keyDownHandler functions, which is causing confusion for the compiler. you don’t need to do a “press” and “release” function, because if the key is pressed, it will equal true, otherwise its false, meaning the key’s not pressed.

  25. Silver says:

    Took me ages to figure out i had written Void instead of void lol. So frustrating :@

  26. Peter says:

    So I assign the keys to A,D,W,S instead of LEFT,RIGHT,UP,DOWN
    and when testing the game, the A(left) key would work normally… but only ONCE and then it won’t work at all, while the others would work perfectly… when i go back to AS3 and change it to the LEFT key instead of A it works perfectly like the others

    help me out, please!

    var leftPressed:Boolean = false;
    var rightPressed:Boolean = false;
    var upPressed:Boolean = false;
    var downPressed:Boolean = false;

    var xScrollSpeed:int = 10;
    var yScrollSpeed:int = 10;

    stage.addEventListener(KeyboardEvent.KEY_DOWN, keyHeldDown);
    stage.addEventListener(KeyboardEvent.KEY_UP, keyRelease);

    function keyHeldDown(e:KeyboardEvent):void{
    if(e.keyCode == Keyboard.A){
    leftPressed = true;
    }else if(e.keyCode == Keyboard.D){
    rightPressed = true;
    }else if(e.keyCode == Keyboard.W){
    upPressed = true;
    }else if(e.keyCode == Keyboard.S){
    downPressed = true;
    }
    }

    function keyRelease(e:KeyboardEvent):void{
    if(e.keyCode == Keyboard.A){
    leftPressed = false;
    }else if(e.keyCode == Keyboard.D){
    rightPressed = false;
    }else if(e.keyCode == Keyboard.W){
    upPressed = false;
    }else if(e.keyCode == Keyboard.S){
    downPressed = false;
    }
    }

    stage.addEventListener(Event.ENTER_FRAME, loop)
    function loop(e:Event):void{
    if(leftPressed){
    background.x += xScrollSpeed;
    }else if(rightPressed){
    background.x -= xScrollSpeed;
    }else if(upPressed){
    background.y += yScrollSpeed;
    }else if(downPressed){
    background.y -= yScrollSpeed;
    }
    }

  27. Colt K says:

    I decided that I wanted to change the direction buttons from the arrow keys to the WASD buttons but when I swap out “Keyboard.RIGHT” for the keycode for “D”, for example, when I play the game after I have pressed either A or D the other stops working. Please help!

  28. Geke-Sulen says:

    Hey Ben,
    Your stuff really helped my project! for the people that want to know how to use buttons for and touchscreen heres my piece of code for it.

    stage.addEventListener(TouchEvent.TOUCH_BEGIN, keyDownHandlerAndroid);
    stage.addEventListener(TouchEvent.TOUCH_END, keyUpHandlerAndroid);

    Multitouch.inputMode=MultitouchInputMode.TOUCH_POINT;

    public function keyDownHandlerAndroid (e:TouchEvent):void
    {
    var target:SimpleButton = e.target as SimpleButton;
    if(jumpKey == target)
    {
    trace(“Key down”);
    upPressed = true;
    }

    if(leftKey == target)
    {
    leftPressed = true;
    }

    if(rightKey == target)
    {
    rightPressed = true;
    }
    }

    public function keyUpHandlerAndroid (e:TouchEvent):void
    {
    var target:SimpleButton = e.target as SimpleButton;
    if(jumpKey == target)
    {
    trace(“Key up”);
    upPressed = false;
    }

    if(leftKey == target)
    {
    leftPressed = false;
    }

    if(rightKey == target)
    {
    rightPressed = false;
    }

    if(shootKey == target)
    {
    fireBullet();
    }
    }
    Enjoy it!

  29. To-mos says:

    i would change the huge if nest to a switch statement more like this.
    switch(e.keyCode)
    {
    case Keyboard.SPACE:
    //do code
    break;
    case Keyboard.RIGHT:
    //do code
    break;
    }
    }

  30. GiaN says:

    If I wanted to do a scrolling screen up and down instead of side to side & have it react to the mouse instead of the keyboard controls what would that code look like? (I’m new to AS3 not sure how much the mouse event & keyboard event handlers differ when it comes to the scrolling of the background) Thanks so much for your tutorials !!!

  31. jaaack says:

    my character spawns in a random spot and not within my map, what shoudl i do #:(

  32. Nathanel13 says:

    To anyone having errors related to Undefined things, the fix is relatively simple.

    Draw your background, select all of it and convert it to a symbol. Name it “background” without the quotation marks. Click the newly created symbol and hit the properties tab on the right. Where it says type “background” without the quotation marks. Test your game and it should work out!

    Nathan

  33. prideofsaigon says:

    To anyone having trouble with Undefined errors, the fix is relatively simple.
    Convert your background to a symbol, name it “background”. Click it, and hit the properties tab on the right. Where you see , type in “background” no quotes. Your game should work now.

  34. Maxine says:

    This was the best flash as3 platformer I found! Made an awesome school project thanks to this tutorial. It really helped me understand as3. Can’t wait for more tutorials!:)

  35. ali says:

    hi excuse me do you are working with layers ? i have different layer one for the villains another one for the background so where i put the code?

  36. Nicola says:

    I followed all the steps, but the result is zero: if I try to move the arrow does not move anything at all (sorry for my english but I’m Italian). even if I try with the tutorial for the game Pong I can not do anything. I am a beginner and this is the only site in the world that explains how to make Flash Professional games

  37. Ben says:

    me too having the background prob. and yeah , i named it background in the instance name..

  38. Ariq says:

    There are errors in the script:

    **Error** Symbol=Background, layer=Layer 1, frame=1:Line 3: The class or interface ‘KeyboardEvent’ could not be loaded.
    function keyDownHandler(e:KeyboardEvent):void{

    How do I fix it?

  39. sameer says:

    Just add

    import flash.events.KeyboardEvent;

    at the top of your code.

  40. Nimish says:

    Brilliant tutorials. I would recommend this site to anyone who wants the fundamentals of game programming. Would love if you could have chapters on exporting Flash AS3 to Android or IOS.

Leave a reply to Ben Reynolds Cancel reply