Getting Started with AS3: The Absolute Beginner ~Part 2~

This is part 2 of 2 of the Getting Started with AS3 series. Click here to view part 1.

OK, so we’ve covered variables, event listeners, and functions. Now let’s check out the code that actually does stuff.

“Action” Code

The final part of code we are going to look at right now is what I call the “action” code — the code that actually does things. Now, in a game, what we could do with action code includes basically anything you can think of: you can move and animate objects, perform calculations, manipulate variables, call functions, and “trace” out data to your output window, just to name a few.

Before we go into examples, you first need to know how to make objects in your game. Whether you call it an object, a sprite, an actor, or a movie clip, all games need graphics on the screen that react to your code.

Creating an instance of a Movie Clip

To create a Movie Clip (what flash calls an object that can have animations), first you just need to draw an object on your screen. A rectangle will work fine.

Next, select the entire rectangle.

And under the “Modify” menu, hit “Convert to Symbol…”
You can also just press F8.

(Tip: If you use a Mac and your F1 – F12 keys do other things when you press them, hold down the [fn] key while you press F1 – F12 to make it work like a normal function key).

In reality, it doesn’t matter what you name your movie clip, but for clarity just name it “player”.

Now here’s the part that does matter. In your properties window, there is a text box called <Instance Name>. Enter the word “player” here.
An instance is a single object in the game with its own name. If you go into your Library window, you can drag more instances of your “player” movie clip onto the screen. By giving each one a unique name you can control them with code. For example, you might have 15 bullets on the screen at once. They are all made with the same Movie Clip, but each is a different instance with a different name.

Now your program knows how to refer to the object on the screen. In your code, you just need to use the instance name, which in our case is “player”. I know I’ve sidetracked a lot from “action” code, but this is all essential for making any kind of game. Now let’s look at examples of what we can do with action code to our player instance.

In order to access the properties of the Movie Clip object (properties include its position on the screen, its size, rotation, which animation frame it’s on, etc), you need to use the instance name, then a period, and then the property (similar to the whole category.SUB_CATEGORY deal we had going on with the event listeners).

player.x = 200;
This code accesses the x-position property of the player object, and sets it to 200.

player.y = 350;
This code accesses the y-position property of the player and sets it to 350.
(Note: y positions are measured from the top down, not the bottom up. That means that an object with a y-position of 0 and an x-position of 0 will be placed in the upper-left corner of the screen.)

player.rotation = 45;
This rotates the player 45 degrees, clockwise.

player.scaleX = 2;
This stretches the width of the player object to 200%. A scaleX of 1 is normal. A scaleX of -1 will flip the object left to right.

player.scaleY = -0.5;
This squeezes the height of the player so that it is only half as tall as normal. The negative sign means that it is flipped over top to bottom.

To check if everything is working, you can use the trace command. This will print any data you ask for onto a special data panel when you run your code. The point of tracing is to see the behind-the-scenes information about your program. To check what the player’s x and y positions are, I would type:
You can also combine trace statements and label them (labels are typed in quotes):
trace(“player’s x-value is”, player.x, “player’s y-value is”, player.y);

If you type all this code directly into your Actions window, without putting it in any functions, the computer will run through all the lines of code once, from line 1 to the last line, and then it won’t do anything else.

Run your code by going to “Control” –> “Test Movie”, or with the keyboard shortcut Command + Return (on a Mac).

You should get something that looks similar to this (although your windows probably look different):

Putting it all together

Ok, believe me, I know this is getting long so we’re just going to put all the pieces together to create a final program showcasing what we’ve learned.

Here it is, see if you can understand how it works on your own. I have put comments next to each line explaining what it does:

var playerHP:Number = 100; // create a new Number variable called playerHP and set it to 100
var enemyAttackPower:Number = 10; //create variable for attack power and set it to 10

player.addEventListener(MouseEvent.CLICK, attackPlayer); // note that it is added directly onto the player (with the period). This makes it only work if you click the player, not anywhere on the screen. Call the attackPlayer function whenever the player is clicked.

setPlayerLocation(); // directly call the setPlayerLocation function, which will run once immediately when we start the game

function setPlayerLocation ():void // this sets up the function, and returns void (nothing)
 player.x = 200; //move the player to 200 pixels from the left of the screen
 player.y = 150; //move the player down 150 pixels from the top of the screen
 player.rotation = 45; //rotate the player 45 degrees clockwise
 trace("player’s x-value is", player.x, "and player’s y-value is", player.y); //output the x and y values so we can see them and make sure everything is working fine

function attackPlayer (e:MouseEvent):void //set up the function that gets called when the player is clicked
 playerHP = playerHP - enemyAttackPower; //subtract the enemy attack power from the current playerHP, and set the playerHP to that new value
 player.scaleX = playerHP / 100; //Set the size of the player to the amount of HP it has left.
 player.scaleY = playerHP / 100; //We divide by 100 because scaleX and scaleY are measured in decimals, so 100 HP is 1, 80 HP is .80, etc.

 trace("The player has", playerHP, "HP left"); //Output how much HP the player has left, just to check

Run this correctly and you should get something like this:

Click the rectangle to deal damage and make it shrink!

Congratulations!! You made your first interactive program a.k.a. a GAME!
(Well, a boring game.)

This tutorial may have been boring, but don’t worry, this was the worst part. Now that you have some idea of what you’re doing with actionscript 3 we can start on a real game. That’s a lot more fun! And now that this is out of the way we are going to dive right in.

I’ll release the first, complete, step-by-step game tutorial ASAP.
Subscribe if you want to hear about the new tutorials as soon as they are posted.

Feel free to make requests about what games you’d like me to make tutorials on. And please, give me all the comments, concerns, suggestions, advice you can think of. I’m very new to this and I hope the tutorial worked out.

Now go use what you’ve learned and build a Pong game!

Good luck on your new game developing career!
Ben Reynolds


19 comments on “Getting Started with AS3: The Absolute Beginner ~Part 2~

  1. Jack Wright says:

    One thing you may want to add is where to actually type the code, and how to open it.

  2. Jack Wright says:

    Scene 1, Layer ‘Layer 1’, Frame 1, Line 23 1084: Syntax error: expecting rightparen before player.

    I’m getting that.

  3. Phil Etzel says:

    In your code above…

    trace(“The player has”, playerHP, “HP left”); //Output how much HP the player has left, just to check

    the test wont work with those quote like that in (“The player has”, playerHP, “HP left”)

    you have curly ones in there.

    Just FYI

  4. Great tutorial! Does HP stand for player’s health? Thanks!

  5. I really liked your whole blog & all the tutorials that you’ve created. I wanted to follow them but too bad that I like writing my code in classes (in different .as files). Please tell me If you have any of those tutorials on this site or if you are planning to get onto that sooner or later. :)

    • Ben Reynolds says:

      Hey there, I’m glad you like the blog!

      I definitely intend to get into programming with separate classes, although there aren’t any up yet. I’ve just been starting off with the very basics, and that means I’ve had to limit myself to coding on the timeline. But believe me, I am excited to finally get into multiple .as classes soon, because that is how I usually code myself.

      Stay tuned — once I finish up the sidescroller tutorial, I’ll probably write a few that deal with making games using classes :-)

  6. zackery says:

    dont know if ur still checking these posts but if possible could you go into depth on using the draw function instead of making an object on the stage. instead write the code to have flash make it for you. other than that i think ur tutorial was fantastic explanation of what things are for and great example of how it works.

  7. Mah360º says:

    Hey, guy, thanks so much, you’d really help me! If you want a suggestion for a new tutorial, you could make a shooting game, just like “Asteroid”. It would be cool if you would do this.

    (Pink avatar? This is unfair!!!)

  8. Liam says:

    what do i use to make the sprite?

  9. Julian says:

    uhm. I duno if its just me but I tried some of your tutorials and I make my actionscript look just like yours in mine but yet it refuses to do anything. I know my adobe works because when I loaded a few of them from your tutorial of pong, those worked. but mine dosent? am I doing something wrong? or am I not working flash properly?

    • Julian says:

      never mind I got it to work. even though I realy didn’t know how lol. I just tested each line step by step and it worked

  10. Richard says:

    Hi, just a question regarding the timeline and it looping. When I have one frame, the timeline does not seem to loop (?). However, if I have two frames the time line loops and the code on frame one is executed again as expected. Is this correct?

  11. Matthew Bond says:

    This is a nice blog. I don’t know where you are in your development right now, but it would be great if you could cover some slightly more intermediate topics sometime. For example, stuff about OOP and how to get your secondary classes to communicate with each other properly. It also seems to be a pain to attach keyboard event listeners from a secondary class, or interact directly with the stage. These are some slightly more advanced topics that are about one step up from what you’ve blogged so far, and I would personally find it useful. One solution is to do almost everything in Main and make everything global, but this is kind of a bad habit, or at least that’s the impression I get. But web searches about doing this the right way are often confusing and discouraging.

    Sorry to ramble. If you happen to know anything about these topics, I think you would be capable of doing them justice. A lot of stuff on StackOverflow is a couple steps too far removed from people just starting out, and it can be discouraging.

    • Ben Reynolds says:

      Thanks for your comment. I agree that some intermediate tutorials would be useful, and I would love to write some eventually. Unfortunately I am knee-deep in my studies as well as work and research, so it’s unlikely I’ll have time to write many more tutorials in the near future. Thanks for your interest, though! Comments like yours keep me motivated to write more. :-)

  12. Giga says:

    Thanks, you really know how to make people understand it!!

  13. Carrie says:

    Finally! An AS3 tutorial that goes into ultimate basics!
    When I first started looking I got knocked down at the first hurdle (e.g. “What does var mean??!” etc)

    It’d be nice if you could note what the 3 variable types are and how to code them / what they mean (I think Boolean is one?)

    I’m still not completely sure exactly when to use a period, comma or colon.. but I suppose that’s just about learning the actionscript language, right?
    And the (e:MouseEvent) confuses me a little..
    Maybe I’ll get the hang of these reading the other tutorials :)

    But other than that, it’s a fantastic tutorial! Best I’ve seen!

    Keep up the good work.

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