Thursday, November 27, 2008

Flash Tutorial: Part 3 of 21

If you have skipped lessons, use the PREVIOUS POST bar on the right side to navigate to the correct lesson.

There are no pictures in this post yet (as of Thursday, Nov 27). I will make some up if I feel like it later, or if someone tells me some part is confusing.

Welcome to Lesson 3! First, we’re going to organize our project a bit more. Some of these are optional, but I recommend doing them all.

1.1 – Timeline frames
First, instead of having the project timeline only being 1 frame, I would make it have more, say, 7 frames. So add frames, and turn frame 7 into a keyframe, and move the code and objects there. Now when you run the project, the first 6 frames will be blank, and on frame 7 you can finally see the character and move him around.

The reason for these 6 blank frames in the beginning are for furture game objects, such as the title screen, the title menu, any cutscenes, and the flash preloader. I usually set aside 10 frames for those, but for now, you can have 6 frames… or 3 frames… or 10 frames… or 20 frames… it’s up to you.

Protip: For now, since there is no preloader or titlescreen, you can save a bit of time each time you test the project by going to frame 1 or 2 and put in
gotoAndPlay(9);

so you don’t have to sit through frames 3-8.

1.2 – Timeline layers

On the timeline, create and add a few more layers, and create a keyframe on frame 10 on each. Name these layers as follows: “code”, “gc”, “code_objects”, and “main”. In the future you can add more layers. Move your “main” to the “main” layer, and the moveTimer to the “code_objects” layer. Move the actionscript code to the code layer, and move the code layer to the topmost layer.

I generally like to keep the code layer blank, and just have the actionscript there.

1.3 – MoveTimer

Make another layer in the moveTimer, and separate the code and the image into the two layers. Now, we’re going to make a slight change to MoveTimer. We programmed it one way in the previous lesson to make it more understandable, but now we’re going to change that so it works better.

In Frame 3, remove the code, so that it doesn’t go back to frame 2.

At the top of Frame 2, write

stop();
this.onEnterFrame = function()
{

And at the bottom, close the bracket.

}

What this does is it will stop Flash at frame 2, and then the “onEnterFrame” code will run, and it will run on every frame. It does the same thing as the first method, except that it’s easier to use, later when we might want to stop the moveTimer. Run the project to make sure it works the same.

Those are enough organization changes for now.

Wall Touching

I hope you’ve been working hard on the wall problem. So after experimenting with it, you probably have noticed that you can’t just use hitTest to detect walls, because once you detect a wall, it’s already too late.

So maybe you can undo your move… so you might’ve had something like this:

if (Key.isDown(Key.LEFT))
{ _root.main.player._x-= moveSpeed;
if (_root.main.player.hitTest(_root.main.ledge))
{ _root.main.player._x+=moveSpeed;
}
}

So you would move the player left regardless of whether or not he was touching the wall, and then you check if he is now touching the wall. If he isn’t, then no problems. If he is, then “no way buddy! You’ve gone past the line. Go back to where you came from!”

So that’s great. Note that instead of +=10 or ++, we’ve upgraded to use a variable. Declare and initialize the variable in frame 1 of moveTimer, and then you can use it as you please.

Now, let’s turn the above into a function, and make it more robust so it can be used for both the y direction and x direction. So back in frame 1 of moveTimer, declare this function

function CheckWalls(xm,ym)
{ _root.main.player._x+=xm;
_root.main.player._y+=ym;
if (_root.main.player.hitTest(_root.main.ledge))
{ _root.main.player._x-=xm;
_root.main.player._y-=ym;
}
}

And you would call it depending on your different directions with parameters (moveSpeed,0), (-moveSpeed,0), (0,moveSpeed) and (0,-moveSpeed). Got it? Good. Test it out!

If it works, great. If it doesn’t, I hope you find your mistakes. In the future, you’ll have to make this function be able to work with multiple walls. Read the challenge section at the end of this article for more details. I mean, I could tell you how to do it now, but isn’t it better to make you learn it?

Globalcode

We’re going to use this soon, so let’s make it. Make a new movieclip symbol, in the same way like moveTimer, and put it on the stage on the gc layer. Unlike all the other objects in the timeline that only exist on frame 10, make globalcode exist on all frames.

Open up globalcode, and put a keyframe on frame 100. on it, put

stop();

Give it an instance name of “gc”, and we’re ready to continue.

Dynamically Creating Movieclips

Before Dynamically making something, we’re going to create a regular bullet and test it out, and make it act like we want it to act.

Task 1: Make a bullet (could be anything, for example, a green circle). For now, test it out by putting it on the screen, and make it move horizontally quickly. Do not modify moveTimer for this.

Newbie help: In MoveTimer, if we held a button down, every frame moveTimer would tell _root.main.player’s _x property (or _y property) to change. We can make it so that an object can tell itself to change. For that, we can use this._x or just simply _x.

Test it out. If it doesn’t work, then… umm… you did something wrong, or you’re missing something. Try again!

Challenge 1: Make the bullet accelerate.

Task 2: Modify the moveTimer so that when you press the space bar, the bullet resets itself to the player’s position. Feel free to nudge the bullet up and down and left and right as necessary*.

* - more on that later

Challenge 2: If you made the bullet accelerate in challenge 1, then make it behave as you want here.

Now whenever you press space, the bullet will reappear where you are, and then travel right.

Now, it’s time to teach you about dynamically making movie clips. We’ll do this pretty quickly without getting into too much mumbo-jumbo.

First, open your library, and right-click on your bullet, and select “Linkage”. In the window that appears, select “Export for Actionscript”, and then that other thing will automatically get selected for you. You can type in anything you want in Identifier, just like you can type anything you want as an instance name. For now, keep it bullet.

Go back into moveTimer, where you hit Space, and replace the code in there with

_root.gc.CreateBullet();

Why? Because I think bullet creation is a generic thing, and that it shouldn’t belong in the moveTimer. This function will get more complicated as we continue, and we don’t want to complicate the moveTimer too much.

Go back into your globalcode, and create a function:

function CreateBullet()
{
trace(“I’m making a bullet”);
}

See if it works.

On Frame 1 of globalcode, put in

var bulletIndex = 0;

Now… the new code.

function CreateBullet()
{
_root.main.attachMovie(“bullet”,”b”+bulletIndex, 200+bulletIndex);
_root.main[“b”+bulletIndex]._x = _root.main.player._x;
_root.main[“b”+bulletIndex]._y = _root.main.player._y;
bulletIndex++;
if (bulletIndex >= 300)
{ bulletIndex = 0;
}
}

OKAY, LET’S BREAK IT DOWN.
- attachMovie is a flash code that.. attaches a movie clip.
- _root.main.attachMovie means that we’re attaching the movie clip the _root.main.
- The first parameter of attachMovie, “bullet”, is which movieclip we’re attaching; remember, it’s not the instance name, or the movieclip name, but it’s the identifier we typed in before.
0 The second parameter is the new instance name we’re giving to the bullet we’re making. In this case, the first bullet we make is “b0”, the second “b1”, and so on. I hope you understand this >_>
- The third parameter is the Depth of the new object. Let’s take a minute to talk about depths.

///////////////////////////////

Everything on the stage has a depth. The depth determines how it will appear to the user, or what overlaps what. Each object’s depth is unique – no two objects share the same depth. If two objects try to share the same depth, the first object ceases to exist.

Movieclips that are dynamically created are assigned depths, between 1 and, like, 1.6 million or something. Movieclips that are already on the stage (such as player, main, moveTimer, etc) have depths between -1 and like, -255,000.

You can find the depth of an object by using its getDepths(); function, or you can give it a Depth by using its swapDepths(someNum) function.

Objects with positive depths can be removed dynamically. Also, objects with positive depths… tend to… linger on the screen. But that’s something more advanced that we’ll talk about later.

/////////////////

function CreateBullet()
{
_root.main.attachMovie(“bullet”,”b”+bulletIndex, 200+bulletIndex);
_root.main[“b”+bulletIndex]._x = _root.main.player._x;
_root.main[“b”+bulletIndex]._y = _root.main.player._y;
bulletIndex++;
if (bulletIndex >= 300)
{ bulletIndex = 0;
}
}

Back to the bullet. So here we give it a depth of 200+bulletIndex, so the first bullet will have a depth of 200, the second 201, etc. Note that the player’s depth is negative, so the bullets (which have positive Depth) will always appear on top of the player.

That completes the attachMovie function. Next you want to set the new bullet’s attributes, or properties.

This is just something you have to remember, when you want to combine a variable and a non-variable into finding an object. So _root.main, as usual, then instead of a period, you open up a square bracket, and type in everything as you want it to appear (so “b”+bulletIndex), and then close the bracket, put the period, and then the property.

So now we set its x and y position to the player, otherwise they’d be zero. You can also set other variables here too. So if on frame 1 of bullet, you have

var xSpeed; //without assigning it

then in CreateBullet you can have

_root.main[“b”+bulletIndex].xSpeed = 7;

Try that out. Declare the variable in the bullet, and assign it in CreateBullet, and use the variable to determine how the bullet moves.

Does it work? I hope so! Continuing on…

Next we increment the bulletIndex. If we don’t do this, then we would just keep spitting out b0’s, instead of going on to b1’s and so on. And then the depth would never change, so our old bullet keeps being reused.

Lastly, we put a limit on the number of bullets we have. We could let it go onto infinity, but… we’d rather not. If you want, you can variabalize the 300 into a variable so you can change it (and refer to it) when you want to.

So… does it work? I hope so!

Okay, so right now, when you create a bullet, it keeps going and doesn’t disappear, until you replace it. But of course, bullets should disappear. You’ve created the bullet dynamically, so it makes sense if you can remove it dynamically. And you can.

In your code which tells the bullet to travel right every frame, you can put in more code, such as checks on whether or not the bullet should die or not. See if you can follow this:

if (_x > 700)
{ delete this.onEnterFrame;
removeMovieClip(this);
}

The delete command is optional in this case, but you can probably guess what it does. The removeMovieClip is another flash function, and it’s pretty self explanatory. It takes in one parameter, which is the movieclip which requires removing, in this case, the bullet is removing itself.

Got it? Good.

Challenge: Make it so that there’s a firing delay of about half a second in between shots.

Challenge: Make it so that the bullet fires in different directions, depending on which way you are facing.

Challenge: If you did the challenge above, then add additional bounds for removing the bullet as necessary. Remember, at this point, you should already be using a lot of variables, so you can easily change things as needed.

Player Nesting/Depth and Animation

We’ll touch briefly on this before the lesson ends. You will probably want to add animation to your player pretty soon, rather than having this blue box walk around. It doesn’t even have a face! So, first, spend a few seconds or minutes or hours drawing or importing the graphics you want. You probably want

Graphic for facing up
Graphic for facing down
Graphic for facing left
Graphic for facing right

Optionally, you can have

Graphic for walking up (and etc)
And/or
Graphic for Shooting up (and etc)

For now, I’ll assume you only need the first 4. Now, let’s talk about Nesting, or Depths.

I was going to make pictures for all of them, but instead, at least for now, I only have pictures for what I'm using in my current game, at the bottom of this section.

It’s really a personal choice, or if you can foresee the future, then you can figure out what’s the best way to do it. So you can have this:

#1111
Your player object can be all the graphics that the player need to go through. So your player object looks like this:

And if you want to change its animation, you would use

_root.main.player.gotoAndPlay(“runright”);

#2222
Each of your specific player animations have their own movie clip. So if you want to change its animation, you would use

_root.main.player.gotoAndStop(“runright”);

#3333
Your player object may have some code, so inside the player object, you have a player_graphic movieclip, which looks like your player from #2222. If you want to change its animation, you would use

_root.main.player.graphic.gotoAndStop(“runright”);

Hitboxes

For now, your player is a square, but if you’re making a 2d-sidescroller, it’s usually not a great idea for a hitbox to encompass the whole player. Part of it is due to the way Flash’s hitTest works; it basically takes the bounding box of the player. So instead we make a hitbox, which is just a transparent rectangular shape, which we'll name "hitbox". But like the graphic, you have several options:

#1111: The whole player is the hitbox

So when you want to have it hit something, you would use

_root.main.player.hitTest();

#2222 There’s a hitbox that’s constant inside the player

So no matter what animation the player has, the hitbox is some fixed area, so

_root.main.player.hitbox.hitTest();

#3333 Each different animation has a fixed hitbox for the entire animation

_root.main.player.graphic.hitbox.hitTest();

#4444 If you’re crazy enough, each different frame in each different animation has its own hitbox.

_root.main.player.graphic.graphic.hitbox.hitTest();

And so on. It’s up to you. For my latest project, I used #3333 for the player animations, and #3333 for the hitboxes.


In the pic above:
1. This is what my "player" object looks like:
2. It's two layers, with two frames total; a graphic at the bottom encompassing both frames (not two keyframes), and two actionscript frames. The first frame is in #3:
3. The first actionscript frame - declaring and assigning a few variables.
4. The second actionscript frame - stop();
5. The graphic layer is just an instance of the object "playergraphic"
6. In my "player" folder, I have, player, playergraphic, and a few other player movieclips.
7. These are some of the sprites I'm using in my game. They're in a different folder than the player folder for better organization.


In the pic above:
1. This is the playergraphic movieclip. It's composed of 3 layers; first layer is blank, just has the different names for the different keyframes. The second layer is the graphic for the particular animation, and the third layer is the hitbox. Note that there is no actionscript anywhere in this movie clip.
2. So, some animation frames just have the bitmap/gif of megaman, because he's not animated.
3. Meanwhile, some animation frames hold different movieclips. If you go into that movieclip,
4. you'll see that it's composed of several keyframes, each which holds an unanimated bitmap/gif. It will loop through these gifs as long as this movieclip is showing.
5. The third layer is the hitbox, which should be transparent but for these pictures I made them slightly visible. The hitbox is different depending on which animation your character is doing.


Challenge: Incorporate the 4 (or more) graphics into your game.

This basically brings us to the end of the lesson. I have an asterisk above which I need to take care of… sigh.

So the asterisk was back when we created the bullet, and it wasn’t centered on the player; it appeared at the top left co-ordinates of the player. FOR NOW, we will keep most of the things like this, but you might have a different opinion. Anyway, there are two… philosophies on this.

Basically, whether or not the 0,0 reference point is at the top left of the object, or at the center. If it’s at the center, then yeah, the bullet would appear in the center of the player, because that is the player’s x and y.

Maybe it’s because as I learned flash, I didn’t know about hitTest, so I used my own way of testing whether or not two objects collided, and it was easier this way. But, whatever, we will keep it like this.

Challenge: Make the bullet appear at the center of the player, without changing the bullet’s or the player’s center reference point.

And that’s it for Lesson 3. Here are all the challenges:

Challenge: Make the bullet appear at the center of the player, without changing the bullet’s or the player’s center reference point.

Challenge: Make the bullet accelerate.

Challenge: Make a firing delay of about half a second between bullets.

Challenge: Make the bullet travel in the 4 directions, depending on which way the player is facing.

Challenge: If the bullet can go in more directions, add additional bounds for removing the bullet.

Challenge: Incorporate graphics into the player so that it has a different graphic for each direction.

Challenge: Multiple Walls. Take note on how we dealt with the special bullets. You might want to make a few more functions in MoveTimer. Use a for loop (or if you want to be extra special, a do/while loop).

Assume 10-15 walls. Don’t go crazy trying to detect 200 walls every frame.

Syntax for For Loop and Do While Loop

for (var i=0; i < style="font-weight: bold;">In the lessons to come: Answers to challenges, scrolling, “quadrants”, Wait, Item Class, Enemy class, Projectile class, and more.

Wednesday, November 26, 2008

Flash Tutorial: Part 2 of 21

Common Problems, and Syntax and Naming Conventions

Before we start with the actual lesson (which will be lesson 3), I’d like to talk about a few things. Instead of you waiting from lesson to lesson on what to do with the program, I should give you enough tools and information for you to go on and practice flash on your own, or make a different program using other tools.

In case you missed lesson 1, or you want to check previous lessons, use the "previous posts" panel on the right of this blog.

The other day, I had Vinh and Jia run through my tutorial. One mistake was that WORD capitalized some of my if statements for me, which transferred to blogger, so that mistake was fixed. But there was a problem that Vinh and Jia both ran into, and it involved naming your instances.

Instance Names

So, a movie clip on the stage has two things – what it is, and its instance name. What it is is the thing in the library, and the instance name is what you use to refer to it in code. It might’ve been confusing because for all my things, I used the same name in the library (“player” and “player”, or “main” and “main”), but they don’t have to be the same. The thing in the library could be “bugolgi” and the instance name could be “sashimi”.

So try it out. Go into your main, and change the player’s instance name to “forcystus”, and run the code. It doesn’t work. Your new mission is to figure out how to make it work, without changing the instance name. Once you got that, understanding instance names is pretty easy.

So that was the main problem yesterday. Jia forgot to name the ledge, and Vinh forgot to name the player, ledge, and main.

Syntax and Naming Conventions

This is mostly for Vinh, or new people to programming. Yesterday I asked Vinh to see if he can upgrade the program to make the character move around using a variable, and he wrote this:

var speed = 5

if (Key.isDown(Key.LEFT))
{
_root.main.player._x = _root.main.player._x – speed;
}

There are 4 things I would change about this.

I would put a ; after the variable declaration, so var speed = 5;

Flash doesn’t require you to put the ; there, apparently, but I think it’s nice to have, and it will prevent problems in the future. ; means the line is over, and that’s it.

I would put the variable declaration on the first frame of moveTimer, and assign it there too, instead of having the variable declared everytime frame 2 is visited.

I wouldn’t use a simple variable name like speed. Remember, you don’t want your variable names to be the same as Flash keywords, so usually I would use something a bit more complex, like moveSpeed or playerSpeed.

Lastly, and this is probably something you have to learn that Vinh didn’t know about, but:

_root.main.player._x = _root.main.player._x + 1;
Is the same as
_root.main.player._x++;
Or
_root.main.player._x+=1;

So in this case, I would write
_root.main.player._x-=speed;

Naming Conventions

I will also add here that flash has a convention for their keywords. First of all, ALMOST none of their keywords will start with a capital letter. So you’ll never see If or For or Do or While, but you’ll see if, for, do, and while. Also, if the function or whatever has multiple words, the first letter of each word beyond the first is capitalized, so you’ll see things like
gotoAndPlay, attachMovie, removeMovieClip, stopAllSounds, and so on.

You can create your own naming convention for your variables and functions, but I generally have the same rule for variables; first word lowercase, then first letter of each word beyond the first uppercase, so things like moveSpeed, xSpeed, bulletIndex, etc.

For me, function names the same as variables, except each first letter capitalized, including the first, so GetRotationSpeedX, CreateItem, etc.

Functions

I talked to Vinh, so I was going to write something about how functions are useful, and why you’d want to use them, but he gets the gist of it so I’m not writing it here. But I’ll write a function you might need to use later, so you can see the formatting of it. So for example, let’s say you want to figure out whether a number is positive or negative. You might need this function:

function GetParity(whichNum)
{
if (whichNum == 0)
{ return 1;
}
else
{
var parity = whichNum/Math.abs(whichNum);
return parity;
}
}

Or in general

function FunctionName(functionparameter1, functionparameter2)
{
functionCode();
//and optionally, return statement;
}

And as usual, parameters are private, or, the variables only exist in the function, or in the for loop or whatever.

Getting and Setting

Not in Flash! You don’t usually need Get and Set in Flash, you just access the property directly. Some useful properties that most objects have include _x, _y, _width, _height, _alpha, _xscale, _yscale, _rotation, _currentframe, and more. Play around with those.

Good Classes to know

Flash has built in classes, like String. If you type String into the actionscript, highlight it, and press F1, you’ll get the help document relating to strings. Another class you will use frequently is Math. Check it out. You’ll use Math.abs, Math.floor, Math.sqrt, etc pretty often.

Text Debugging

A lot of times, especially when things aren’t working, you’ll want to put in trace events around to see what exactly your code is doing. So you might want to have something like

trace(“the index is “ + whichNum + “ and the boundary is “ + whichBound);

Textboxes

You might want to play around with input text, or dynamic text, or static text. Static text is just regular text. Input text is a text field where you can input information, and Dynamic is where it displays information. For both Input and Dynamic, they each have an instance name, so fill that out, and access the information like this.

var whichNum = Number(_root.iNum.text);

_root.dNum.text = “The number you have chosen is “ + whichNum;

Comments

Comments are always useful. Here’s the syntax:

// comment on this line
/*
Comment section
*/

So… this “lesson” was mostly to help you experiment, instead of just sitting there, waiting from lesson to lesson. You can probably create a “hello world” application now, and maybe some small calculator application.

Monday, November 24, 2008

Flash Tutorial: Part 1 of 21

Hello everyone! I've decided to write my own tutorial on how to build flash games. For now, I will host them on this blog.

Introduction:
For now, I'll pretend I'm just writing to my friends, so the language will be less formal than if I was writing to the whole world. So anyway, this is my flash tutorial, with my own methods and all that. You can read other tutorials and maybe their methods are better, but I'm going to try to explain my methods easily and all that so hopefully you'll stick with me. After you're done with the tutorial, maybe you can expand and improve on my methods with your own unique style, or you can adapt to other people's methods and work out which way is the best.

So why am I writing this? Because Jia kinda asked me to - well, he wanted help on how to start programming in Flash, so this is it.

Requirements:
I do not require you to know any or a lot of flash. I know a lot of you don't know flash, so I'll try to make it as easy as possible. For those of you that require flash, let me know, and I can arrange it for you. I have a 60 meg zip file with Flash MX 2004, so let me know if you need it.

After you get Flash, experiment it with a bit, make a few movies, play around with drawing things and making shapes and tweening. After that, you're ready to read this tutorial.

Lesson Plan:
It says at the top "Flash Tutorial: Part 1 of 21", but I just made up that 21. At the end of this tutorial, you'll have a screen, with a player character, and you can control him by pressing the directional keys. There will be an object on the screen, and if you touch it, the object will "disappear".

In this lesson, I will try to get you to make a game as fast as possible. That said, we'll use some methods in this tutorial that are easier to understand, yet less efficient.

Anyway, enough talking. Let's start!

Step 1: Setting up the environment
For my tutorial, you can use Flash MX 2004 or Flash CS3 (or newer). Start a new project, set the actionscript to 2.0, Flash Player 7.0, height and width to 640x480, frame rate to 30fps, and background to white. Actually you can change these to whatever you want, except the actionscript and the flash player, but for now, stick with me.

You can have whatever panels or layout you want, but I generally only use the main bar with the Tools, the Properties Window, the Actionscript Window, the Timeline, the Color/Swatches, and the Library. I don’t use any of those Projects/Components/etc windows that Flash CS3 might start with.

Newbie Help: You can close as many windows/panels as you need, and then in the View menu bar you can choose which panels you want, and then you can drag them and resize them and lock them onto your flash window wherever you want.

Step 2: The Timeline
In later tutorials, you will have many layers on the timeline, as well as many frames, but for this demo, we only need one layer, and one frame. Click on this frame, and open up the actionscript window, and type in

stop();

This will tell Flash to stop at this frame, and not play anymore frames, or repeat this frame, or whatever.



Diagram: My Flash environment; which windows and panels are open, general layout, timeline. The movie clips will be added below.

Step 3: The 5 movie clips

In most of my games, there are 5 movie clips you need to make a flash game:
1. MoveTimer
2. Player
3. Ledge
4. Globalcode (optional)
5. Main (optional)

In this tutorial, we’ll skip the globalcode movie clip, and we’ll make the Main movie clip without discussing whether or not your particular game needs it. In any case, it’s good to have.

Step 3.1 – Main

Main is where I keep all my game objects – players, ledges, enemies, etc.

Newbie Help: Remember, there are 2 common ways to make a new movie clip: you can choose Insert – New Symbol, or you can draw something, select it and right click on it and Convert To Symbol.

For now, choose Insert, and make a new symbol, make sure it’s a movieclip symbol, and call it main. Flash will proceed to let you edit the new movie clip, but leave it empty and go back to the Scene. From your library, drag “main” to the stage, place it at x=0 and y=0, and give it an instance name of “main”.

Newbie Help: To change a movieclip’s properties, open up the properties window. You may need to check the advanced properties – change its instance name to “main”, and move it to x=0 and y=0.

Step 3.2 – Player

Draw a blue square, and set its dimensions to 40x40. Select it, right click on it, and click Convert to Symbol. Make sure it’s a movieclip symbol, and call it “player”. Now that you have it in your library, delete the “player” you have that’s on the stage.

Open your “main” movieclip in your library by double clicking on it. Now you are editing it; drag your “player” blue square from your library onto the main, and place it around x=10 and y=10. Name this instance “player”.
Save and run the project. If you did it correctly, your player should appear on the screen.

Step 3.3 – Ledge

Repeat what you did in Step 3.2 with player, but this time make a 20x20 red square, call it ledge (or wall, or whatever, but for this tutorial call it ledge). Do the same things with it, but place it at x=100 and y=100. If you run the project again, it should appear as expected.

OKAY! I hope you understand everything we did so far. If it’s confusing, I don’t recommend continuing. It’s basic flash so far – make a movie clip, put it on the stage, and voila, it’s there. Or put a movieclip within another movie clip, and it appears. It’s all pretty basic, so if you’re having trouble with this part, I recommend learning some more basic flash.

Now comes the real stuff.

Step 3.4 – MoveTimer

MoveTimer will be one of your most important movieclips. MoveTimer will take care of your player object, as well as most of the user input. So far, everything we’ve done is pretty basic, but after this step you’ll have the first real step to making a game. So, pay close attention.

See, Flash works with movieclips and frames, and if you put code in a frame, it will run the code each time it hits that frame. So what we need in a game is code that tells the computer when a player hits a key, and what to do when the key is pressed. So what we need is code that is run on every frame. There are many ways to achieve this effect, but in this first tutorial, I’ll teach you the one that makes the most sense, at least in English.

So how do you get Flash to read the same frame/code over and over? Simple! You make a frame with code, and on the next frame, you tell flash to play the previous frame! And that is an endless loop, which runs every frame.

So for example, you can put some code on frame 1, and on frame 2, you have

gotoAndPlay(1);

And voila! It works. So we’re going to do just that… with a small change.

So go back to Scene 1, and use the textTool to write the word “moveTimer” on the screen. Make sure in the properties window that it is static text, not input text or dynamic text. Select the word, and convert it to a movieclip symbol, called “moveTimer”. Change its instance name to “moveTimer”, and move it to x=-40 and y=-40.
Remember, this moveTimer is on the root, not in the main movie clip where the player and ledge reside.

Instead of frame 1 having the code and frame 2 redirecting back to frame 1, instead we’ll have frame 2 with the code and frame 3 redirecting to frame 2. So on frame 3, write

gotoAndPlay(2);

So it’s the same thing, but one frame later. We’ll discuss why we did this later.



Diagram: The timeline and the actionscript frame of moveTimer

Newbie Help: To create more frames in a timeline, just click on the timeline, and right click somewhere and you can see a menu of options of what you can do. Choose “insert keyframe” on frames 2 and 3.

After adding the code on frame 3, go to Frame 2 and put in this code:
trace(“this is moveTimer tracing every frame”);

Save the project, and run it. If you did it correctly, then on every frame (so 30 times per second) it would write the above line into the output window. If you did it incorrectly, check the error messages for clues, and make sure everything is spelled correctly and has the right capitalization.

Step 4 – User Input

Okay, we have our Main. We have our MoveTimer. We have our Player inside our Main. We have code that runs on everyframe. We’re ready to start.
First, go into moveTimer, and delete or comment out the trace. We don’t need it. So first think to yourself – what do you want to happen? You want to make it so that if you press a directional button on the keyboard, your player will move in that direction. So, in pseudocode:

if ( I am pressing the up key)
{
Player moves up
}

Let’s first attack the “player moves up” part. Before scrolling down, you should already have a pretty good idea on what the answer is. When you’re ready, read the next line.

if (I am pressing the up key)
{
_root.main.player._y--;
}

Got it? If not:

You want to modify the player’s y position. That’s where the _y comes from.
You want to move it upwards. In flash, that’s in the negative direction. That’s where the - - comes from, or the -= or whatever.
Which _y do you want to modify? The player’s. So that’s where we have player._y.
Where is the player? He’s in the main. That’s where the main is.
Where is the main? He’s on the root. That’s where the root comes from. Putting it all together, we have
_root.main.player._y--;

If you’re coming from other programming languages, or from Actionscript 1 or 3, I hope this is still somewhat understandable.

Now, the next part is probably pure flash syntax and code, so you can spend a while going through the help files, or I’ll just give it to you here:

if (Key.isDown(Key.UP))
{
_root.main.player._y--;
}

When you start typing the K, flash will autocode the rest for you so it’s not so bad. It’s pretty simple to understand the code. Now, fill in the rest for left, right, and down, Save the program, and run it. If it works, congratulations. If it doesn’t, check any error messages and fix them. There might be spelling errors, case sensitivity errors, maybe bracketing errors… but after a while, everything should work.

Voila! You have a working game now. Fiddle around with variables – try to get the guy to move 10 pixels at once instead of just 1, or if you want another challenge, try making a game where pressing the buttons just accelerate and decelerate your character. After you’re done, we’ll talk about the hitTest.

Step 5: hitTest

One of the more important functions in game programming is the hitTest. The hitTest is exactly that – a test whether or not two objects hit each other. So it could be a player hitting a 1up mushroom, or a bullet hitting an enemy.

So back in our game, we have the player on the main, and we also have the ledge on the main, and I assumed you called it “ledge”. For now, think of it as an item or something we can touch. Hit Detection with walls is a little more complicated.

The code for hitTest is really quite simple. So, back in moveTimer, type in this.

if (_root.main.player.hitTest(_root.main.ledge))
{ trace(“my player is touching the ledge”);
}

That’s all there is to it. You can check the helpfile for more info on this, but long story short, hitTest is a function that movieclips have, and it takes in a parameter which is the movie clip to compare it to, and it returns a boolean value, either true or false.

This means that

_root.main.player.hitTest(_root.main.ledge)

Will give the same value as

_root.main.ledge.hitTest(_root.main.player)


But since moveTimer deals with the player, it makes more sense to write it out the original way.

So, save and run the program, and as you expect, if you move your player over your ledge, it will trace that message.

Now we want to make the object disappear, and then the lesson will end. For now, we'll cheat a little. Replace the trace command with

_root.main.ledge._y = -9999;

And then, when you run the project and hit the ledge, it will "disappear" off the screen. Really, it just goes upwards all the way to -9999, but for now, it looks like it disappears.

That’s the end of lesson 1! You now have a character on the screen, and it will move in different directions based on what key you are pressing. You also have an “item” on the screen, and you can touch it. Now save your project, and copy it, so you can fiddle around with it before you move onto lesson 2. We will begin from this point in lesson 2, so you should make another copy of your project which you can fiddle around with.

Between now and the next lesson, I’ll give you a few challenges. If you’re a newbie, read the few paragraphs below to help you get started on some common flash syntaxes, or use the Flash help file.

Challenge 1 – make it so that when you press a direction, the player would move 10 pixels instead of just 1 pixel in that direction.

Challenge 2 – make it so that when you press a direction, the player accelerates or decelerates depending on what direction you pressed.

Challenge 3 – The hitTest works fine for grabbing items, but not so well for walls/ledges. Program the game so that it works with walls/ledges. Note that the answer to this will be given in the next lesson, but it’s a good idea to think about what you have to do.

Newbie help: Declaring variables
In Flash, declaring variables is easy. Sometimes you don’t even need to declare it. Just use:
var thisNumber = 2;
or
var thisText = “Hello”;
You don’t have to tell the variable it’s an int or a string or whatever. If you want to learn how to declare other things, such as arrays, check the help file.

Newbie help: Declaring and Calling Functions
Sometime in the programming of games or anything, you’ll probably need to learn how to declare and call functions. Well, you’ve already used a few functions, such as hitTest, but you’ll want to make your own, so you can re-use code and whatever else.
To declare a function, do thiu:
function FunctionName()
{
//function code
}
And whenever you need to call that function, just type it out, like
FunctionName();
Or
indexNum = FunctionName();
In flash, you don’t need to use void or to declare the return type or whatever. It’s pretty in that way. It’s kinda lousy for error checking, but otherwise it works fine. Also, if you have parameters, you don’t have to declare them or give them any restrictions or whatever.

For other flash syntax, check the helpfile. For the next lesson, if you don’t know anything about for loops, I recommend reading up about those.

In the next few lessons: walls/ledges, arrays, better organization, dynamically adding and removing movie clips, animation, “quadrants”, text, Wait, and a little bit about scrolling.