Sidescrolling Platformer – Part 13 – Enemy Interactivity

As I announced in the last post, I am extremely busy right now. Luckily for you, a member of the community has already stepped up and written a Part 13 for this side scrolling tutorial! In this tutorial, you’ll learn to create “bumper” objects for your enemies to interact with, which will let them patrol back and forth. You’ll also look for collisions between the player and the enemies, so you can take damage in your game. Cool!

I’ll hand it over now to the newest guest writer around here, Ed Nordmeyer (thanks, Ed!)

Ben covered creating enemies and making them disappear when they’re shot in lesson 12, so in lucky lesson 13, in this guest tutorial, I’ve picked up where the last lesson left off in the side scrolling platform game.

This will cover making the enemies move, how to block them in so they’ll patrol in a simple side-to-side motion, and have them interact with your player if they touch you. Following in Ben’s footsteps, if I had to choose between making the code readable or making the code ultra efficient and take up the least amount of lines, I tried to make the code as easy as possible to understand.

Creating the Bumper class

If you’ve followed the tutorial steps so far, you’ll find that creating the bumper class is very, very similar to the other classes made so far. For the artwork, I just made a square that was about a 25×25 pixels in size. I created this block on the background layer outside of what the player screen shows when you’re running the game. We’ll go back and made the blocks transparent later, but for now I’d recommend making them easy to see to help placing them on the screen from our code.

Create a bumper rectangle in Flash Professional cs6

Once you’ve created the bumper square, select the bumper, and convert it to a Movie Clip symbol.  As mentioned in the last lesson, go to the Advanced section to link this object to the “Bumper” class. If you need a refresher on what all the settings are for, refer to Part 10.

Creating a custom class for the enemy bumper

Create a “bumper” class named The bumper code looks like this:

package {
    import flash.display.MovieClip;
    public class Bumper extends MovieClip{

        public function Bumper(xLocation:int, yLocation:int) {
            // constructor code
            x = xLocation;
            y = yLocation;

            addEventListener(Event.ENTER_FRAME, bumperloop);

        public function bumperloop(e:Event):void{
            //code here

Adding Bumpers to the Background with Code

We could add bumpers to the game by copy/pasting the block we created, but that means they’d stay in the same spot when the platforms changed when we moved to level two. To be able to make the bumpers work with the platforms, I added the bumpers to the level from the main program. The code is similar to the addEnemiestoLevel() code you’ve seen previously. I called this function addBumpersToLevel().This code is passed two variables, whihc tell the program where the 25×25 blocks will be added to the screen. You’ll want to make one bumper on the left and one on the right for each platform where the enemies are currently standing.

Up where the variables were declared, add an array for the bumpers. I placed mine right by where I added the enemy array, and it looks like this:

var bumperList:Array = new Array();

Right under the line “addEnemiesToLevel1():” from the main code page, add the following code to put two blocks next to the first enemy you encounter in this game. The co-ordinates are the X and Y points for where the bumpers should be placed. You can go back and add more later, but for right now I’m just going to corral the one enemy closest to where we start the game. (Yep, I’m from Texas, and we corral stuff ’round here.) Repeat this step for any  additional enemies you’ve added to the game.

function addBumpersToLevel1():void
    addBumper(500, -115);
    addBumper(740, -115);

In the main code page, by the addEnemies function, add this to finish calling the bumpers and adding them to an array. We’ll need the array later.

function addBumper(xLocation:int, yLocation:int):void
var bumper:Bumper = new Bumper(xLocation, yLocation);

Changing the Enemy Class So They Move

So far, so good. We’ve got bumpers now, but without a moving enemy, they’re kinda useless. What we want to do is have the enemy move until it hits a bumper, then reverse direction. Reopen the enemy class ( and make the following modifications:

package {
    import flash.display.MovieClip;
    import;public class Enemy extends MovieClip {

        private var xSpeedConst:int = 2;
        private var flip:int = 1;

        public function Enemy(xLocation:int, yLocation:int) {
            // constructor code
            x = xLocation;
            y = yLocation;
            addEventListener(Event.ENTER_FRAME, loop);

        public function loop(e:Event):void {
            if ((flip%2) == 1){
                x += xSpeedConst;
            } else if((flip%2) == 0){
                x += (-xSpeedConst);

        public function removeSelf():void {
            trace("remove enemy");
            removeEventListener(Event.ENTER_FRAME, loop);

        public function changeDirection():void{
            trace("x ="+x);

Many of you are going to be familiar with the “%” sign, or the modulus operator. For those that aren’t, it’s a mathematical function that means when you divide a number by something (in our case, two) does it divide cleanly or is there a remainder left over?

This code initially sets the variable flip to 1 and starts with the enemy moving to the right. Flip mod 2 gives you a remainder of one, it means flip is an odd number, so our speed is a positive number. Once we hit the bumper, we increment flip by 1 using flip++. Now flip is an even number (flip mod 2 has no remainder,) so change the xSpeedConst to a negative, which means our enemy will now move to the left. Hit the left side bumper, flip++ makes the number odd, and back to the right again.If you compile and test now, you’ll see the bumpers appear, the enemy starts to move… and moseys right through the bumper. So let’s fix that.

Did Someone Hit Your Bumper?

I was going to make a car insurance joke here, but decided against it. Instead, in the main code add this to detect if the enemies hit bumpers with the following code.

//corralling the bad guys with bumpers
if (enemyList.length > 0){ //enemies left in the enemyList?
    for (var k:int = 0; k < enemyList.length; k++){ // for each enemy in the enemyList
        if (bumperList.length > 0){
            for (var h:int = 0; h < bumperList.length; h++){ // for each bumper in the List
                if ( enemyList[k].hitTestObject(bumperList[h]) ){
                    // trace("hit bumper");

Did an Enemy Hit the Player?

Please note I added a commented line in here where you could add code to determine what happens to the player when they run into an enemy. If you’ve read the health bar tutorial, you could make your health go down 50%, or if you don’t believe in second chances, you could call a a gameOver() function that then takes you to a gotoAndStop(“gameover”) frame. Your choice, but that topic is worthy of another tutorial.

//player and enemy collisions
if (enemyList.length > 0){ //enemies left?
    for (var m:int = 0; m < enemyList.length; m++){ // for each enemy in the enemyList
        if ( enemyList[m].hitTestObject(player) ){
            trace("player collided with enemy");
            //code to damage player goes here

Make the Bumpers Invisible

Last but not least, we don’t want the bumpers cluttering up the landscape. After you’ve added all of the bumpers you want to the screen to keep your enemies safely patrolling where they should stay, I went back to the addBumper code and changed the visibility to false after they’re created.

function addBumper(xLocation:int, yLocation:int):void
    var bumper:Bumper = new Bumper(xLocation, yLocation);
    bumper.visible = false;

Okay, that’s it for this tutorial! We covered adding bumpers, making the enemies move, and how to check if the enemies either hit a bumper or hit you. As a shameless plug for my game that I made using Ben’s tutorial, please visit this and give me a 5 star rating, and I hope to be invited back as a guest speaker again soon!

Ed Nordmeyer


Source Files:

49 comments on “Sidescrolling Platformer – Part 13 – Enemy Interactivity

  1. mojmon says:

    WoW Tutorials are getting more and more exciting :)) Thanks for this helpful tutorials AS3 Game Tuts.

  2. immrsam says:

    I just finished part 12 yesterday.. perfect timing :)
    Only thing im having trouble with, is removing remaining enemies from the first level and adding enemies to the following levels. Any help will be great

    • nitacawo says:

      Just finished tuts and had some pain to remove them myself. The proper way to remove enemies and bumpers due to array system would be.
      creating a function.Its not explained here but if you followed tuts you would probably try ++ like Tyler and I did first. It wont work properly due to array system. You can read more info here.

      So it would look like this.( you can copy this one but next example is better)
      function removestuffLong():void
      for(var z:int = bumperList.length; z > 0; z–)

      for(var z:int = enemyList.length; z > 0; z–)
      enemyList[z-1].removeSelf();//z-1 because array starts from 0!

      Copy this one.

      function removestuff():void
      while( enemyList.length>0)

      and add to the function nextLevel():void{

      //rest of the code we wrote in previous tuts.

      I hope this helps someone.

  3. tyler says:

    If you know how to clear all enemies of a ‘level’ so they do not duplicate into the next (if left unkilled) would be uber helpful. :)

    • tyler says:

      I worked it out – thought I’d post my solution here to help others :)

      function nextLevel():void{
      // Remove the enemies from current level
      for (var i:int = 0; i < enemyList.length; i++) { // for each enemy
      enemyList[i].removeSelf(); // remove from current level
      // then just the normal code
      trace("Next Level: " + currentLevel);
      if(currentLevel == 2){
      addEnemy(620, -115);
      addEnemy(900, -490);
      addEnemy(2005, -115);
      addEnemy(1225, -875);

      • Nick says:

        Hi Tyler, I am having trouble with the code you provided, maybe you can help me further?
        How do you have your Level 1 enemies added in the code to start? Can I email you for further help?

      • Nick says:

        Hi Tyler, I’m having some trouble with the code you generously provided. It won’t remove the enemies. If I take out the “if(currentLevel == 2){gotoLevel2();” it does work. Any suggestions? Thanks!

        • Dreamonic says:

          Hi Nick,

          The for-loop is the only piece of code that removes all enemies from the current level. It states that, for every enemy there is left in the list of enemies, the enemy has to be removed from the list (through the method provided in this tutorial series). Be sure to put it above “currentLevel++”, or else the for-loop will delete every enemy in the next level.

  4. Bindlestick says:

    Hey, are all your source codes going to be in cs6 now?

    • tyler says:

      I believe this tutorial was provided by another user.

    • Ben Reynolds says:

      It depends. I personally have CS5, but this guest writer used CS6. I know this isn’t ideal for most people because you might not be able to open the source files, and I’m really sorry about it. The problem is that CS6 can only export as low as a CS5 file, and CS5 can only export as low as CS4, etc. Perhaps if we set up a team of volunteers with different versions of Flash, we could pass the files around step by step and “translate” them into lower and lower formats.

  5. TheLibyan says:

    Wow these are really great. Hey would you mind putting up tuts for something a little complicated? A tut where your bullets fire in the direction of your cursor. Like If my character was standing still and my mouse was at the top left corner, the bullet would fly out of my character and go to the top left corner. And also a tut where your characters head is always facing the mouse and as the mouse moves, the head rotates to face it. It would really help my and my team (school project for a competition.) Thanks

    • Ben Reynolds says:

      Thanks, I definitely could write a tutorial about that — it isn’t actually as difficult as it seems. The problem is I am really busy at the moment, so I might not get around to it for awhile. It’s definitely on my to-do list, though.

  6. Allan says:

    How can i make different enemies with different images?

    • Ben Reynolds says:

      One quick way would be to have your enemy Movie Clip have multiple frames, each with its own image. Then have a variable in your enemy code, for example “enemyType”, which is an int. When you add the enemy to the stage, also run the code myEnemy.gotoAndStop(enemyType), and it should work. There are many other ways to implement this, you just need to play around and see what works best for you.

  7. RedDevil says:

    how to remove the bumpers of each levels, pls reply

  8. Will Mahan says:

    Thanks a million for the great tutorials. I’ve been hammering away at AS3 (and coding in general) for about a year now, even went so far as to take a flash class one semester, and as much as I “want” to learn, it seems like it’s a hard sell.

    I don’t know if maybe I’ve been around it long enough that it’s starting to soak in, or if maybe your teaching style works really well, but either way, I’ve struggled less with your tutorials than the previous lessons I’ve tried to absorb.

    Your explanations are clear and easy to understand, at least for me, and I appreciate all your efforts. Maybe I’ll get the hang of this someday, after all …

    Once again, thanks for taking the time to share your knowledge.

  9. Ciara says:

    hi guys, has anybody figured out how to remove the bumpers when u level up, been trying for ages but keep geting errors :(

  10. Rick says:

    Hi, great tutorial, a massive thanks for making it! Just one quick question: How would I create timed platforms and lifts? Would I just create movie clips and edit their frames and re-position for each frame or would i do it in the AS code?

    Cheers :)

  11. Nico B says:

    Hey, i have an urgent question, any reply at all would be greatly appreciated.
    You see, i realized that if i edited the “enemy” MC, the one linked to its class, in any way, the enemy would just go right through the bumpers and ignore the bullet hits, as if it stopped functioning and was just going along its way, is there any idea as to the reason for this?

  12. Kerta L says:

    Pretty good, although it seems that fast movements can cause the enemies to escape the bumpers at times.

  13. Dreamonic says:

    Hey Ed Nordmeyer,

    First of all thanks for another great tutorial!

    Second, I went to your website to look around and explore your games.
    I noticed the design could be spiced up a little. :P

    Care to collaborate? I’m an informatics student, and I love to design websites!
    If you’re interested, you can click my username above this post to go to my website, and check it out. You’re free to leave your contact info on the contact page, so I can contact you.

    Keep up the good work, guys!



  14. Colt K says:

    Could you possibly make a tutorial telling how to make the enemies have a bit more AI. Like maybe have them move towards the character.

  15. FenderFalcon says:

    I’m new to AS3. years ago i made side scroll games with AS2 where you could add code directly to movieclips. One game i had where the player could throw a grenade and it would bounce off walls and the floor before exploding. If i was to make this again in AS3 and have the grenade as a grenade class, could i pass hittests into the grenade or would i have to code the grenade movement into the main timeline as a function?

  16. ganesh says:

    wow, its full of treasure..
    well I have decided not to touch adobe flash cs x, instead I will use only flashdevelop, does it make sense=============

  17. Jonathan Grenier says:

    How do the get the X and Y coordinate from the object player on the scene from the class ? I tried calling the function with more parameters from the main code but it only give error code abouta missing left brace and I did not added any right brace I just sent more parameter when I created my var Enemy. Pretty please someone help me.
    on the line:
    var enemy:Enemy = new Enemy(xLocation, yLocation);

    I want to add more parameter but it only give an error of missing left brace when I try to add more parameter like this and change the constructor to work with those 2 additionnal parameter. :

    var enemy:Enemy = new Enemy(xLocation, yLocation, player.x, player.y);

    Anyone know how to fix this please ? Maybe there is another way to get the player object’s coordinate from the class maybe ?

  18. Jonathan Grenier says:

    I made it work you can now delete the above reply and answer this:
    Why do the Enemy event does not appear on the stage if it has a symbole inside the Enemy symbole which is linked to the class ?
    And why does the Enemy events do not die anymore from the bullets if the Enemy symbole which is linked to the if it has 2 or more frames but it die just fine it it has only 1 frame ? How do I make it have more frames to change its graphic while still die from the bullets ?
    I’m clueless. 1 frame = work fine, more frames with labels = no enemy death
    1 symbole in Enemy symbole = no Enemy events on the stage

  19. Bex says:

    Loving the tutorials!!! I really really wanna add coins to my level though…….i tried on my own and failed miserably if anyone can help id really appreciate it :)

  20. Sampada says:

    Here is the game i designed using this tutorial… have a try…

  21. Laura says:

    Hey Thanks a bunch for this tutorial! It really helped :D
    But from the first flash you posted, as a demonstration, there was ally interactivity, and climbing ladders. I was really hoping to see those :/ It’s been months since your last upload!
    Can’t wait!!

  22. Will Mahan says:

    I did this tutorial awhile back and have just recently revisited it for a new project. The enemies I created quite obviously have a front and a back and needed to not only change direction but face towards the new direction as well. I solved the problem easily by adding “this.scaleX *= -1;” to the bottom of the “changeDirection” function.

    I realize this tutorial is older but it’s still plenty relevant. Also, I skimmed the comments and didn’t see this mentioned, but if it is, I apologize in advance.

    Thanks again for all your hard work.

  23. Broc says:

    Not sure if anyone still monitors this, but if I wanted to add a item/wall/floor/etc using this source code that on contact it will teleport you back to the start position, how would I go about doing that?
    I want to use these items like lava, so once you hit them you start from the beginning of the level.

  24. JoeFrank says:

    Hey guys, I’m having trouble figuring out how to add walking animation for the AI as they move

  25. Isaac Clarke says:

    I am almost AS3 illiterate but . . .

    How do you effectively remove Bumpers from a level?

    I tried using the methods (array list) posted in the comments but I get Compiler Errors or sometimes Output Errors?

    Is there any other way to make Enemy Patrol? Like with Timers or such?
    I want to make my enemy patrol an area, and if the player is near enough, will shoot bullets at an interval. But I have no idea how to type it. O_O

    Also, how do you add Enemy animation? Like walking and death animation? I tried using the same animation state but they just go through the bumpers and bullets.

  26. Avery says:

    Awesome tutorial, but are you going to continue it?

  27. Manny says:

    Hi Ben i try all your tutorial now i am planning on implementing a health bar for all of my enemy but what happens is only one enemy have a health so only one die when the hp went to 0 what should i do Ben??

  28. Matt says:

    So I’ve gotten everything covered in place and its working fine. My issue now is that I’ve added animations to the enemy characters so they actually walk when the move back and forth. Now they just pass through the bumpers and the player like I turned off their collisions. Any ideas?

  29. I made an animated enemy and then hitTestObject not work when fired at the enemy. How to fix it? I want the enemy to be animated.
    I also noticed that in your example, sometimes the protagonist falls into the earth. How to fix it? And I would like to learn how to add different enemies.
    Thank you. At least if you know the answer to one of the questions, contact me at my e-mail or comment here.

  30. […] enemies and enemy interactivity to it using online tutorials. The tutorials can be found at this website. I also helped Jeff work on the Presbyterian Church T-shirt […]

  31. flash says:

    thx for a great tutorial

  32. Flash says:

    Thanks for the tutorial but was just wondering if instead of using bumpers it would be easier to use maths, like:-

    var radius=150; //adjust this to set how far object goes left or right
    var angle=0;
    player.x=radius*Math.sin(angle); //put next 2 lines inside loop function obviously change player to enemy

  33. Rick says:

    ArgumentError: Error #1063: Argument count mismatch on Bumper(). Expected 2, got 0.
    at flash.display::Sprite/constructChildren()
    at flash.display::Sprite()
    at flash.display::MovieClip()
    at TheHunterWithinv0_fla::MainTimeline()

    I got this error. How to fix it?

Leave a Reply

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

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

Facebook photo

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

Connecting to %s