Sidescrolling Platformer ~Part 6~ Parallax Scrolling and Multi-Layer Visuals

Welcome to the sixth installment of the AS3 Side Scrolling Platformer tutorial series.

The background scrolls. The player collides with walls, and can jump (and even double jump). Our laws of physics have been established, and the basic mechanics are coded. In other words, we have built a working prototype. In this tutorial, we will step our platformer up a notch by adding in fancier visuals, and even the capability for layers of parallax scrolling, which will give the game the sense of depth which it is lacking.

This is a pretty good tutorial, which will really improve your game if you’ve been following along. When all is said and done, this is what we will accomplish:

(click to activate, and control with the arrow keys)

As you can see, while none of the basic game mechanics are different, I have added a lot of content since the last tutorial. To keep things organized we need a…

Plan of Attack

Here is a brief outline of the steps required in this tutorial to transform our once-bleak prototype into a vibrantly illustrated game.

  1. Rename the only layer inside the background object. This will be the Collisions Layer.
  2. Convert everything inside the current background image into a new object nested inside the background, which contains everything the player will collide with.
  3. Create a new layer on top of the collisions layer inside the background, which will be the Visuals Layer.
  4. Create a new object in the visuals layer which will contain all of the visuals of the game that the player won’t collide with.
  5. Draw the environment to your heart’s content inside this object in the visuals layer.
  6. Change the code so that hit-testing only considers the collisions layer.
  7. Outside of the background object, create a new layer behind the background and draw the parallax-background. Convert this into a Movie Clip object.
  8. Program the parallax-background to scroll at a different rate than the normal background.

There we have it. 8 Steps. During this tutorial, we will go through each step, one at a time.

Step 1

Double-click on the background object sitting on the stage so that you are editing inside it. Then in the Timeline Panel, double-click on the layer name and set it to “Collisions“.

This layer will contain any objects in the game which the player can collide with. Right now, this means the bare-bones outline of the background walls, floors, and platforms.

Step 2

Select everything inside the background object. Hit Modify –> Convert to Symbol… (Hotkey F8) to turn the current outline of the background into a Movie Clip. I named mine the Background Collisions Container, and I set the Registration to the bottom-left corner.

After you create the Background Collisions Container object, give it the instance name “collisions“, and set its position to X: 0 and Y: 0 using the Properties Panel.

Then, to keep everything centered, go back to the stage and set the position of the entire background object to X: 0 and Y: 500. This will return the background to its approximate location, although if you run the game you’ll notice that it isn’t in the right place. This is because the location of the background object in-game relies solely on code, not where we place the object on the stage. (We can use this to our advantage when we build larger levels.)

So click back on frame 1 of the main timeline, where we wrote the code, and in the actions panel update the variable declaration of scrollY so that its initial value is 500.

var scrollX:Number = 0;
var scrollY:Number = 500;

Also, just to make things more interesting, I took advantage of the fact that we can now double jump and I modified the drawing inside of the Background Collisions Container. After a bit of basic drawing using the rectangle tool filled with black, and no outline, I came up with the following. I used thick lines to minimize the errors of our current collision system. You can either try to replicate my own background, or just download my source code at the end, or you can try to create your own customized level map.

Also, before we get too far into this, go back to Scene 1 and set your stage’s background color to something other than white (unless your game needs white). I chose a soft, sky blue.

Step 3

Inside the main background object, create a new layer above the Collisions Layer. You can do this by clicking the small square button shown in the image below, or by selecting Insert –> Timeline –> Layer. Rename it so that it reads “Visuals”. Right now, it has nothing in it. We’ll change that in steps 4 and 5.

Step 4

Create a new Movie Clip symbol in this layer (Insert –> New Symbol), which will be the Background Visuals Container. This is going to contain any objects which the player will not collide with.

Once you hit “OK”, you will be taken inside this object to start editing. Draw a small test mark, line, or dot, just so the object has some substance in it, and then return to Scene 1 by clicking on the button in the upper-left corner of the stage. Double click on the main Background to edit it. Making sure you are in the Visuals layer, open up your library panel and drag an instance of your Background Visuals Container onto the stage. Use the properties panel to set its x and y location to (0,0).

Step 5

The infrastructure of our background is set up. Time for the good part — drawing the visual part of the background. Double click on the instance of Background Visuals Container which you just placed on in the background layer. Delete your previous test-mark, and begin to draw whatever crazy area you can dream up. After we update our code, the player will not hitTest against these shapes, so you don’t need to be too strict about staying within the lines.

I’ll walk you through the process I went through to make the demo, but as always, feel free to improvise.

I used the rectangle tool to block-in the basic platforms with ground-color. About halfway done covering up the platforms.

I curved two of the corners of my rectangle tool for the platforms (found in the Properties Panel).

Tracing along the faded-out shapes of the collisions background, with the new tool. Nice effect!

I finished blocking-in the base color for the area.

I created 3 new layers on top of the "Base Ground" layer, and switched to the "Base Grass" layer.

I changed the rectangle tool options for the grass, including new rounded-corners.

I used the new rectangle tool to add a green base-color on the top half of each platform.

After repeating for each floor segment, the visuals' base-colors are all set.

Switching to the next layer to add details.

I drew a small clump of grass with the Brush Tool, and converted it into a graphics symbol.

Copying and pasting these grass-details around the map, I adjusted some of their brightness levels to add variety.

Decorate the map to your heart's content by duplicating a bunch of any details you draw.

I decided to draw a cool palm tree to add to the background, and converted it into a symbol so I could add multiple instances of it to the background. You can use either of the Other Effects layers to make sure certain objects are in front of one another.

Hooray! A little attention to detail works wonders for a game! The visual aspect of my background is done :-)

Hopefully your background turned out successfully… or you decided to use my source code, which is fine, too :-)

Step 6

Return to Scene 1 and click on Frame 1 of the timeline so you can see your previous code in the actions panel.

The changes we need to make are very, very simple: change the collision code from checking the entire background, so that now it will only check the “collisions” object inside the background.

How do we accomplish this?

Change:

back.hitTestPoint( // ... etc, etc

into:

back.collisions.hitTestPoint( // ... etc, etc

every time it appears in your code.

Test your game, and you should be able to frolic in your new-drawn paradise. Congrats.

Step 7

Hey, I know what you’re all really looking for: parallax. An easy topic which delivers a lot of bang for the buck.

Create a new layer on the main timeline, which I named “parallax sky”, and drag it beneath the background’s layer. (In fact, I created a couple more layers as well, to stay organized… one for the player, which goes on top of the background, and an additional one on the very top which only holds code — no objects on the stage.)

The other layers are for organization. Focus on the parallax sky for the moment.

In the parallax sky layer, draw a few clouds (or whatever you want your parallax-background to be) and convert them into a symbol. Set its x and y position to (0,0). I gave mine the instance name: sky.

Double click on the sky object to edit it, and finish its art. It should be pretty large in size, but it’s going to scroll slower than the background, so it isn’t required to be quite as large. I made mine a little bit bigger than it needs to be, just to stay on the safe side.

I drew a couple clouds using the Brush Tool, and duplicated them to make it larger.

After completing your parallax sky, return to Scene 1 to finish up.

My final stage setup.

Step 8

We’re almost done! Just a little coding to tie everything together.

Check out the actionscript for scrolling the sky. Inside the main game loop, at the very bottom (directly beneath back.y = scrollY), add the following 2 lines of code:


sky.x = scrollX * 0.2;
sky.y = scrollY * 0.2;

Wait? That’s it!!?

— Yep.

Think about it. A parallax-background is just another background which scrolls at a different rate. We’ve already done the code to figure out what scrollX and scrollY location the regular background is at. For every 1 pixel the player moves, the normal background will move 1 pixel. So all we need to do to take into account a parallax-background’s distance is multiply the scrollX and scrollY by a constant.

The smaller the decimal we multiply by, the more distant the clouds will appear.

We could create another layer with bigger clouds, and set its x to be the scrollX multiplied by 0.5. These would move faster than the other clouds, but still slower than the normal background.

Or we could even create a parallax-layer in front of the normal background, and multiply the scrollX and Y by a constant greater than 1. The possibilities are endless. And the more layers you add at different depths, the more realistic and 3D-ish your game will seem.

Try out the result!

You can download the source here.

If you happen to make anything cool with this, I’d love to see your creations! Leave a comment below, or email me at as3gametuts@gmail.com with a link to your games :-)

Of course, this tutorial series is still far from over, so you might want to hold off on publishing your masterpieces until later. I’m still debating what to write about in the next part, but it might be collecting coins and items around the area.

Enjoy! And if you find this helpful, spread the word!

Advertisements

47 comments on “Sidescrolling Platformer ~Part 6~ Parallax Scrolling and Multi-Layer Visuals

  1. Jaime says:

    Excellent. Loving it and looking forward to the next installment – most definitely!

    There’s a little glitch where the character falls between the steps on the ground and walks around inside, but it only happened once and I couldn’t get him to recreate the incident. I don’t know what happened there.

    • Ben Reynolds says:

      Thanks! I know the collision detection system between the player and the background can be a little glitchy at times. When I was writing the Part 3 of the tutorial, I added the semi-faulty collision system as a simple and easy way to make the game work…. but now I’m starting to regret my haste. Perhaps in the next tutorial part, I’ll work out the kinks in the hit-testing as well as add a new feature.

      • Jaime says:

        Eh, it’s free, it’s fun, and it’s a learning experience. I’d say we can’t complain all that hard ;)

        Though, no doubt, I’d be happy to see how to work some of those kinks out. I’ll wait and see what the next installment contains. Mmmmm mystery and suspense. Ha.

  2. Mon says:

    Ben you have been such a great help for our project. Your definitely going to be stated in my acknowledgement! keep up the great work so much win :D

  3. ashwin says:

    Hi Ben
    This is so awesome and easier to understand. Every tutorial you cover seem to be a wonder in its style of simplicity and the results are too good to be true. Scrolling and parallax scrolling have been made more easier thanks to your tutorials. Thanks for the great efforts you are putting up in teaching the game community., keep doing such similar wonders mate

    The only thing i was a bit confused was the significance of the registration points. How does flash calculate the width and the height from the registration points?? I tried with keeping the registration point at the center and adding the half the width and the height to check for collisions and it went sadly wrong. Could you please explain how registration plays its role in calculation

    Cheers

    • Ben Reynolds says:

      Hi ashwin, I’m glad you’ve enjoyed my tutorials! (Sorry about my slow response.)

      It sounds to me like your attempt to keep the registration point at the center should have worked… so I am a little confused myself. The Registration Point of an object is just the pair of x and y coordinates that Flash uses to keep track of where the object is. If you set the x and y position of an object to be (0,0), and set the registration to the top left corner, the object’s top left corner will be located on the top-left of the stage. If you set its registration to its center, its center will be located directly on the top-left of the stage. If you set its registration to the bottom-center, you wouldn’t even be able to see it on the stage because its bottom would be lined up exactly on the upper-left of the stage.

      No matter which registration you choose, the width and height will stay the same. The one thing that does change, is where certain parts of the object are located relative to the object’s zero point. For example, in my game I’m using the bottom-center, so when I hit-test with the ground, I just use player.x and player.y for that point. If I was using the center as my registration, I would still use player.x (because the x’s zero-point hasn’t moved), but I would use player.y+player.height/2, because the zero-point is higher this time by half the height of the player, so we need to add that back on to compensate.

      Has this helped make things clearer? Hopefully I’m not rambling ;-)

      • ashwin says:

        Hi Ben thanks for your time to reply and you sure are not rambling. I am waiting to see more of your awesome tutorials. It would be great if you could teach us some Math concepts and also OOP way of doing the scrolling.
        Thanks once again for the great tutorials

      • ashwin says:

        I have sent my work based on this tutorial, please take a look

  4. This is excellent. But the problem is that the player still goes inside the background. How can we fix that ?. Can you please in your next tutorial also teach how to deal with buttons. Also how did you make the hands and the legs move and also the moving platforms in your World Of Adventure.

  5. Renz says:

    Wow! This is excellent and it was really helpful cant wait for the new one :D

  6. ashwin says:

    @Ben
    Can you help me with my registration point doubt above??

  7. Kemik says:

    This is really great and I find your tutorials very helpful, but I’m confused at Step 2. You’re talking about two different background objects, right? When you say “select everything inside the background object”, what do I do? Double click on the background like in Step 1 to create the Collisions layer? What about the “back” object we made earlier? Please help. ^_^’

  8. Kemik says:

    Something maybe you can help me out with… My character keeps bouncing off of things that aren’t there. I think it only happens when he’s moving to the left. I don’t know what it is, but if I try to move from the right side of the level to the left side, he bounces off some invisible wall and gradually breaks through it, then gets caught on another, and another, etc. all the way to the left side. It’s very annoying and it makes it hard to test other things. I’d really appreciate if you have any ideas of what might be happening and why. :)

    • Ben Reynolds says:

      Hmmmm… that’s strange… I’ve never seen that happen before. I have two suggestions. First, double check that your instance names of the background are correct, and match up with your code. The only thing that the player should be colliding with is back.collisions (which is the collisions layer inside the background object). If those names/code are all correct, then edit your collisions layer, and make sure there is nothing in it that you don’t want to collide with.

      If you can’t figure it out, you second option would be to download my source file. Try copying + pasting my source code into your project, and see if it runs well. If it still doesn’t work, that means your code must have been fine, so your objects on the stage must be the thing which is messed up. Try examining the objects inside my source project, and see if you can identify the difference between your and mine which is causing the problem.

      Let me know how everything goes!
      Ben

  9. Chris says:

    I was wondering How would i Add Other Objects and make them not scroll with the screen but actually be present? I followed your tutorial and i have an AI script i designed I place it in and the object doesn’t even appear on the screen unless i place it near the player. And when i do that it scrolls with the screen as if it was a interface object. I was wondering if you could explain this to me? Id be greatly appreciated, Is there a way to not scroll the other objects or enemies with the screen and leave them alone for interaction throughout the level?

    Thanks again,
    Sincerely,
    Chris

  10. Devi says:

    Thanks so much for these tutorials! This is exactly what I was looking for! They’re clear and make sense, more than I can say for a lot of the other actionscript stuff out there…

    There’s one thing I was confused about though. for Step 2, you convert everything to a movieclip called Background Collisions Container and move it up. How do you then select the entire background object to move it? If I click the background it just gives me the info for the collisions container…. I feel like this is extremely simple, but I don’t know……..

    Also, it’s my goal to make a room-based platformer. Perhaps sometime in the future can you consider adding in how to move the player through different rooms, and “remembering” where the player enters the other room (like taking the top or bottom passage… etc).

    Thanks so much for creating these tutorials!

  11. Jacob.Reardon says:

    Hey Ben,
    I love your Tutorials, I’ve followed them for a while and they are very good, I have a question though, after step 6 I get a massive swarm of the error code
    Type Error: Error #1010: A term is undefined and has no properties.
    at platform_tutorial_fla::MainTimeline/loop()
    If you were able to tell me what I did wrong while following the tutorial please let me know.

  12. LyyrDaremoh says:

    Hello,
    I was hoping that you could help me out, I’m doing something wrong, but I don’t know what. I put the parallax sky in and the code and the clouds, but when I put the code in the actionscript, it says that the term sky is undefined, and I used the source code as well that you give at the end, and I got the same error, could you tell me what I am doing incorrectly?

  13. I’d firstly like to thank you for your tutorials Ben.

    Although I’ve been playing about with Flash for years, I still followed you step by step and felt that you supplied a good set of foundations that any beginner or advanced person can follow. Some of your wording can be a little confusing but anyone with a little intellect can work it out purely from the information you have supplied. I’m glad to know there are people like you helping the people in need.

    Secondly, I’d like to mention a method I’ve used for collision detection, instead of checking the players collisions only once per game loop you can put the collision check in another loop.

    I’m not too good at explaining but I’ll try writing it like this:

    Main Game Loop
    –> Collision Loop (5 iterations)
    –> Check to see if any part of the player is hitting anything

    So once per frame you’re getting 5 collision checks.

    This will slightly reduce performance in “the most optimal light” but adds a lot to player stability as fast movement might teleport you past a wall on a single check.
    This checking multiple times a frame for player collision decreases the chance of the player getting past it.

    Another safety feature is keeping walls thicker than 20px but I’m sure nobody needed to hear that from me.

  14. Cm Guy Ü says:

    Thanks man for spending time making this tutorials. Really appreciated. Hope to have more from you. Thanks for sharing! :-)

  15. Cm Guy Ü says:

    Can you link me the tutorial #7? thanks again. Keep it up.

  16. Zim_of_rite says:

    I’m really confused, and, as a result, incredibly frustrated.

    In step 2 it says to select everything, according to the picture everything but the player is selected, and the player is grayed out. My player is selected with the rest of the background.

    • Zim_of_rite says:

      OK, I think I got passed that, but now I’m even MORE confused, what is the ‘entire background object?’

      I have NO IDEA what you’re talking about in this tutorial so far to be completely honest. I’m only on step 2 and I feel like punching my monitor.

      • Ben Reynolds says:

        Sorry about that. I tried to be as clear as possible, but making games is inherently tricky.

        By the “entire background object”, I was just referring to the object we named “back”.

        The reason I am referring to it this way, is because the point of this tutorial is that we split the “back” object into multiple parts. Each part has a different function, but they are all still a part of the “back” object. We create a part inside the “back” object for the visuals, which has the important function of making the game look pretty, but we don’t want the player to be able to collide with that part, or else he would be blocked by trees and grass in the background. So to fix this, we create another part inside the “back” object”: the collisions part. In this part, we only draw lines that we want the player to collide with. This way, we can do a collision detection between the player, and back.collisions, and the game will run smoothly.

        I hope this helps clarify things! Let me know if you are still having trouble :-)
        Ben

        • Zim_of_rite says:

          Aaah, thank you!

          I love your tutorials, by the way. They’ve helped me a lot.

          • Zim_of_rite says:

            One more question, is the Background Visuals Container supposed to be empty? Or am I doing something wrong?

          • Ben Reynolds says:

            Yes, it starts out empty. Then you are free to draw anything you want in it. The things you draw in it won’t affect the gameplay, they just make the game look nice.

        • Zim_of_rite says:

          It’s me again! And guess what? I’m confused!

          OK, so I draw everything like you said, but the visuals are moving with the player. I did everything your tutorial said to do (I think) but visuals still move with the player instead of staying over the black lines like they should.

          • Ben Reynolds says:

            Did you make sure that the visuals are “nested inside” the back object? What I mean is, you need to double-click the back object on your stage so that you are editing inside it, and then create a new layer. This way, the visuals and collisions layers are both inside the same container (the back object), so if you move that container it should move both the collisions and the visuals.

  17. Jonathon O'Neill says:

    I’m in a wall

  18. troy silber says:

    Hello i’m Troy
    I can’t get my person to collide with the key. I tried copying over your code but when I do, I go to the key and hit it and it freezes and says I have the 2007 error. What should I do?

  19. Dreamonic says:

    Hi,

    I am currently using your tutorial as a guideline for a school project, I’ll let you in on the final version when it’s finished! Thanks for the tutorials, keep it up!

  20. ribbs23 says:

    Ben, fantastic tutorial, I can’t believe how much can be achieved with so little coding and your teachings are providing so much insight into action script. There are a couple of glitches namely the getting stuck in the steps, but I see it as a challenge to try and improve the level. I would like to add sound but maybe that will be covered in another tutorial. For now I’m going to enjoy expanding on this little game. Awesome!

    Thanks again

  21. jim says:

    My god! plain awesomeness, I wanted to build a side scroller since ages and now withi your tutorials I can implement my idea perfectly. Thanks a lot!!!!!

  22. Emma Mahr says:

    Hi Ben,
    Thanks for all the great tutorials. I’m a little stuck at the moment though. On step 6 when I change the code I get an error

    TypeError: Error #1010: A term is undefined and has no properties.
    at gametrialfixcollision_fla::MainTimeline/loop()

    I’m not sure if this has something to do with the layers or maybe the character (who I notice for you is on a separate layer which I don’t have and don’t know how to fix) haha

    Any ideas?

    Thanks in advance
    -Emma

  23. Amazing tut , i making my version of this will try improve graphic and progress more on script and adding portal :D

  24. Loren says:

    Nice tutorial. Thank you. I did this part as instructed and works great. I like however to add another background with the command ‘scroll’ for the second level.. Is there any way to add parallax scrolling for each one of the levels?

  25. Flash says:

    For anyone interested if making a lift that goes up and down try this.Not sure if to post this here like.

    var radius:Number=650 //adjust this to set how far object goes left or right
    var lift_speed:Number=0;

    //put these 2 lines in loop function
    back.visuals.visuals_lift.y=radius*Math.cos(lift_speed);
    lift_speed+=.03//change this here to change speed of lift

  26. Flash says:

    btw the above code will also work with a lift that you want to go from left to right etc just change the cos to sin

  27. SiCong says:

    Hah! This tutorial is awesome! But I think you forget to show everybody how you achieve character flipping horizontally when pressing right or left key.

    here’s my code:

    if (leftPressed)
    {
    xSpeed-=speedConstant;
    player.scaleX=-1;
    }
    else if (rightPressed)
    {
    xSpeed+=speedConstant;
    player.scaleX=1;
    }

  28. Random Guy says:

    Hey Ben, awesome tutorial, but how do you make the collisions container invisible, but still functional? I have ugly bits of it sticking out of the edge. Thanks XD

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s