As I’ve stated on here before, nothing drives me crazier than seeing people using tables for website layouts when CSS is better and easier when you know what to do. One thing I had trouble with when I was just starting out was a two column layout with the left column matching the height of the right column. Eventually I figured it out and it’s a lot easier than you think. Remember, there’s always more than one way to do things, but this is the simplest way I’ve found to do this.
Nothing major, we just have a container div and the two column divs. The first thing you might notice is that the right column is above the left column, I do this because it allows me to position the two columns with only a couple of lines of CSS.
All I’m doing here is setting the right column’s left margin to equal the width of the left column and then setting the left column’s position to absolute and it’s top position to zero. This moves it up and into the position we want. The main problem I always had was getting the left column to stretch to the height of the right column which is usually a big deal if they both have different background colors. I’ve solved that problem here by not giving the left column a background color and giving the color I’d want the left column to have to the container div. Now when the right column stretches, it will stretch the container div and it will look like the left column is stretching with it.
This works in all the modern browsers and it’s what I use here on my blog. I don’t know if it works in IE6 because I don’t really care.
Last week ActiveTuts put up a quick tutorial about building a sliding menu paddle, which isn’t anything too complicated but it was the first time I’d done anything with the built in Tween Class in ActionScript 3. Usually I’d use something like Tweener or TweenMax, but I thought I would see what you could do with this. What I decided to make was something that I would have loved to have been able to make with code when I was just beginning to learn AS3, a Flash site with sliding content. This would have been something I would have used movieclips I created in Flash and then created keyframe tweens to get the effect I wanted. This isn’t the most complex thing to create but it will help out beginners.
Here’s what we are going to build:
Start a new Flash file (AS3), mine’s the default – 550×400 with a white background and the framerate at 24. This is about the functionality, not the design, you can add that in after you get the all working. Save it as whatever you want, I called mine TweenSite.fla. Next, using the Text tool (T), type out something like button 1 on the stage. Make sure the button is set to Dynamic Text and the instance name is buttonText. This will allow us to control what the button says in our ActionScript file.
Now turn the text into a movieclip, F8 or Modify > Convert to Symbol. Call it MyButton, set the registration point to the top left and check the Export for ActionScript box.
Delete the MyButton from the stage, we’re going to add it using ActionScript. Finally, one the Document Class field, type Main. This will link our ActionScript file to the .fla. If you don’t know how the document class works, there’s a great video at gotoAndLearn.com.
And that is everything we are going to make in the .fla. Everything else now will be created with ActionScript.
Create a new ActionScript file, File > New… > New ActionScript File. Call it Main and save it in the same folder as your .fla. Instead of writing all the code in the .fla or even in just one .as file, we are going to build this OOP style, to make it easier to customize after it’s been built.
Here’s the code we are going to start with in Main.fla:
package { //We have to import the classes we are going to use importflash.display.MovieClip;
publicclass Main extendsMovieClip { //This creates an instance of the button we made privatevar button1:MyButton = new MyButton();
publicfunction Main():void { //This calls the init function which gets everything going init(); }
privatefunctioninit():void { //This adds the button to the stage addChild(button1); } } }
If you test this now, you should just be able to see the bottom and right side of our button. This because the position of something added to the stage is automatically 0,0. So just add this under addChild(button1):
1 2
button1.x = 30;
button1.y = 50;
This just positions our button the stage. Now to make this work the way we want to, we need more than one button, up with the other variable add this:
1 2 3
privatevar button2:MyButton = new MyButton(); privatevar button3:MyButton = new MyButton(); privatevar button4:MyButton = new MyButton();
What we’re doing here is making three more instances of the same button, but we’ll use our code to change the text. Underneath button.y = 50 add this:
Here we are adding the three other buttons to the stage and positioning them 40 pixels apart. Now if you test it, the buttons will all line up vertically but they all say button 1! So, how do we fix that? At the bottom of the init function add this:
Now if you test the movie, the text should have changed to what we have here. Now as it stands now, our “buttons” don’t really act like buttons. If you mouse over them, you won’t get the hand cursor that tells people that it’s a clickable button. We can fix this a couple of ways. One way would be in our Main.as file to set the buttonMode to true and something called mouseChildren to false for each button, but that would be a lot of code, and if we wanted to change something, like the names of buttons, we would have to change a lot. The simple way to do this is to make a new ActionScript file and put the settings in there. So create a new ActionScript file and save it as MyButton in the same folder as our other files. If you named your button something else, you have to name this file the same as your button because our Main file is going to import these settings and apply them to our buttons. Here’s the entire code for our MyButton.as:
publicclass MyButton extendsMovieClip { publicfunction MyButton() { //This gives movieclips the same properties as buttons, so the hand cursor appears buttonMode = true; //This stops the text from inside the MyButton movieclip from being selectable mouseChildren = false; } } }
Now if you test the movie, you’ll see that now the hand cursor appears and the text isn’t selectable. This is the main advantage of OOP, with a few lines of code, we have affected our entire navigation. Now, let’s add the gray block to our movie. Create a new ActionScript file and save it as Block.as. Here’s the code for Block:
publicclass Block extendsMovieClip { publicfunction Block() { //Draws the block using actionscript to keep file size down //First part is color, second is the alpha graphics.beginFill(0xCCCCCC,1); //This draws a rectangle(x,y,width,height) graphics.drawRect(0,0,102,36); graphics.endFill(); } } }
Now back in Main.as we have some code to add. First add this up with the other variables:
1
privatevar block:Block = new Block();
Same as with the buttons, we are creating an instance of our Block class. Next in the init function, at the top, before all the buttons put this:
1
addChild(block);
Now at the bottom of the init function add this:
1 2
block.x = button1.x;
block.y = button1.y;
Now when we test our movie, the block will appear behind the top button. Next we’ll give our block something to do, at the top where we are importing the MovieClip class add this:
This is going to allow us to have mouse events and tween events in our Flash movie. Next with our other variables, add this:
1
privatevar barY:Tween;
Here we are creating our first tween. Now we need to tell our tween what to do:
1 2 3 4 5
privatefunction onNavClick(e:MouseEvent):void { //First we say what to tween, what property to affect, set what kind of ease(if any) we want to use, where to start the tween, where to end, how long to take, and the true means the time is in seconds, if it's set to false the tween is in frames
barY = new Tween(block,"y", Back.easeOut, block.y, e.target.y,1,true); }
I’ve described what the Tween does in comments in the code. Next we need to add some listeners to call this function so it actually does something, what I usually do with listeners is create a function addListeners():
We need to add a listener to each button so that the block knows which button to go to. Inside the Main function add:
1
addListeners();
Now if you test the movie, you should get this:
OK, now let’s make those buttons control something. What we are going to do is just make four big blocks that slide into view. Once again, we aren’t designing anything we are just building the functionality. The block can be easily replaced with images, movieclips or external .swfs. To do this we are going to make a new ActionScript file and call it ContentBox.as. We’re going to make all the boxes in on class instead of making a separate one for each box. It’s just easier and it’s not too hard to build more custom classes for your own stuff later. Here’s the code for ContentBox:
Really simple stuff here, we’re just creating four boxes that are 345 by 360 and positioning them along the x-axis. I’ve also made each one a different shade of gray that way we can see the boxes move but we won’t blind ourselves with bright colors. Next, up with the variables, put this:
1
privatevar contentBox:ContentBox = new ContentBox();
Same stuff we did with the buttons, so you should know what’s going on here. If you test your movie now, you’ll see the first box and part of the second box, which isn’t really what we want, we just want to see the first box. To do this, we’ll just add a mask to our stage. Make a new ActionScript file and save it as MyMask.as. Here’s the code:
Pretty much the same as our ContentBox class, but with this our mask, the color isn’t going to matter. Now back in our Main.as file, add this code up with the other variables:
1
privatevar myMask:MyMask = new MyMask();
And then add this at the end of the init function:
1 2 3
addChild(myMask);
myMask.x = 185;
myMask.y = 20;
Now if we test this, there’s a red box over top of the first gray box, which I don’t think is quite what we’re going for here. So let’s add this line of code right under the last stuff we added:
1
contentBox.mask = myMask;
Now if we test it, the first gray box is back and we can’t see the other box anymore. Now we have one final thing to do and it’s not that major, we’re just going to apply the Tween code we used on our navigation to the boxes to make them slide into view when a button is clicked. First off, add this to your other variables:
1
privatevar contentX:Tween;
Next we need to add these listeners, which are pretty much the same as the other listeners, they are just calling another function:
Here we’re just using if statements to see which button was clicked and then telling contentBox what to change it’s x value to. Now if you test the movie you’ll see contentBox slide to the color that corresponds with the button we clicked on.
I hope this helped you out, this framework should be pretty easy to customize and allow you to build stuff pretty quickly.
On to the final step in making our shooter! You can go back and check Step 1, Step 2, Step 3 and Step 4 if you missed something. In this step, we’re going to add a score and set up our rocket so it can be hit by the enemy ships. This one’s going to be pretty simple, the point of this whole tutorial was to show the basics of building a game in AS3. If you want to take it farther, it won’t be that difficult and will be a great learning experience.
The first thing we are going to do is use the Text Tool (T) to add a dynamic text block to the stage. I put mine in the bottom left, but you can put it anywhere. Make sure that it’s set to dynamic text, not static or input and give it an instance name of scoreTxt. Because it’s dynamic we can change the contents with ActionScript and it’s only going to take a few lines of code to do this. First, we need to add this to the bottom of the other variables:
1 2
//Sets the variable score as an integer var score:int = 0;
Next, in the rocketMovement function, right before the closing bracket, add:
1
scoreTxt.text = "Score: "+ score;
This sets the text inside our scoreTxt textfield with the text() method. We’re telling it to display the word Score plus our variable score, whose value we will assign next in our Enemy class. The reason at we are putting this line of code in the rocketMovement function is because we are listening for any changes to score every frame. We could create a new function just to update the score, but since rocketMovement is doing what we want anyway, we can just add it in there.
Now in the Enemy.as file we just have to had one little line of code. Put this in the moveEnemy function:
1
_root.score += 5;
Now, when the enemy ship is destroyed, the game will add 5 to the score.
The easiest way I’ve found to end the game is to use a Boolean. In the main code, I created a variable called dead, typed it to Boolean and set it to false:
//tests to see if the enemy ship has hit the rocket movieclip if(this.hitTestObject(_root.rocket)) { //if it has, dead is set to true
_root.dead = true; } //check to see if dead equals true if(_root.dead == true) { //remove listener and the ship from the stage removeEventListener(Event.ENTER_FRAME, moveEnemy);
_root.removeChild(this); //add the game over text to the stage var gameOver:GameOver = new GameOver();
_root.addChild(gameOver);
gameOver.x = 125;
gameOver.y = 100; //move the rocket off the stage
_root.rocket.x = -100;
_root.rocket.y = -100; }
I’ve created a moveclip that says Game Over, I named it gameOver and checked the Export for ActionScript box. When an enemy ship hits our rocket, the game will remove all the ships from the stage, move our rocket off of it and add the Game Over movieclip. The reason we are moving the rocket movieclip off the stage instead of removing it is because we put it on the stage in our .fla, if we had added it with addChild() we could remove it easier, but it’s not that big of a deal.
That’s it! Now you should have the basics of a shooter game that you can build on, adding lives and more than one kind of enemy shouldn’t be too hard. I hoped this helped and now I have to figure out what to build next.
This was probably the hardest part of my AS2 game to switch over to AS3, because all the code in AS2 was in the actual .fla. Since the code for both the laser and the enemies were actually on the stage, it wasn’t too hard to make them interact. But since we are making this is in AS3 and the code of the laser and enemy ships are in their own AS files, we have to figure out a way to have the enemy ship code know where the lasers are on the stage. The easiest way to do this is to just add a movie clip to the stage and put the lasers inside it. This way, we can keep track of where the lasers are and how many there are. So, the first thing we have to do is add this code to the top of the main code in your Flash file:
And down where the laser is added to the stage, change it to this:
1
laserHolder.addChild(newLaser);
Alright, that’s all we are going to change in the main .fla. Next, we have one thing to add to Enemy.as, put this in the moveEnemy function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
//Make a loop that contains the number of lasers on the stage for(var i:int = 0; i < _root.laserHolder.numChildren; i++) { //add a new movieclip for each laser on the stage var laserTarget:MovieClip = _root.laserHolder.getChildAt(i); //check if any of the lasers has hit this enemy if(hitTestObject(laserTarget)) { //if it has, then remove this enemy ship from the stage and remove all the listeners removeEventListener(Event.ENTER_FRAME, moveEnemy);
_root.removeChild(this); //this removes the laser
_root.laserHolder.removeChild(laserTarget); //this removes the laser's listeners
laserTarget.removeListeners(); } }
I commented the code because it’s easier than explaining it here. We just have to make one more change or we’ll get an error. If we left it like this, the laserTaget.removeListeners() line would give us an error. The reason for this is pretty simple, we are trying to access a function in the Laser.as file from the Enemy.as file and that function, removeListeners() is a private function. In order for Enemy.as to access this function, we just need to switch it to public. So in Laser.as, change:
In step 1, we made our ship move around the screen and in step 2, we made it so it can fire lasers. Now we have to give it something to shoot at.
This is similar to what we did with the lasers in step 2 but to get the enemies to appear on the stage, we just need to do a few things, declare a variable that will set the number of enemies and add a for loop to our code.
Make your ship in your .fla, convert it to a movieclip, call it Enemy and Export it For ActionScript, it should say Enemy there as well. Delete the ship from the stage, you just need it to be in your library.
Now add this to your list of variables in the code you have in your .fla:
1
var nrEnemies = 6;
and then at the bottom of your code, add this:
1 2 3 4 5
for(var i=0; i<nrEnemies; i++) { var enemy:Enemy = new Enemy() addChild(enemy); }
Now, just like with the lasers, we have to make a new ActionScript file to control our enemies, File > New > New ActionScript File. Save it in the same folder as your .fla and the Laser.as file, call it Enemy.
Pretty simple, we’re importing MovieClip and Event because those are the only two classes we’re using for our Enemy class. Now let’s fill this out. We have four variables, add them after the class statement but before the function:
Just like with our Laser class, we have the variable _root to bring in our stage info. Next we set up the variable for the speed our enemy ships are going to travel, we aren’t assigning it a number here because we’re going to set it up so the number is random for each enemy. timer is going to be used to change the direction of our ships so they they aren’t just flying straight across the stage. And dir is the direction that our enemy ship is going.
Pretty much the same as our Laser class, we’ll run the addClass function when the enemy ship is added to the main stage and then every frame we’ll run the moveEnemy function. And since we’ve added some event listeners, we better write the functions. First, we’ll write the addClass function.
Inside our addClass function, we have the same line as in the Laser class, _root = MovieClip(root);. But we also have addShip();. This triggers an addShip function instead of having another event listener. Add the function right after addClass.
What the addShip function is doing is assign the enemy ship’s position, x is always 600, off the stage and the y is random. We multiply the number Math.random() generates by 400 so that the
enemy will appear anywhere between 0 and 400. And we finally assign a value to our enemySpeed variable. Math.ceil rounds the number off and we generate a speed between 1 and 5. Next we’ll add the moveEnemy function.
This is where we’ll control the movement of our enemy ship. We assign the subtract enemySpeed from the x position of our enemy ship it have it move right to left across the stage. Next we check to see if the enemy ship’s x position is less than zero. If it is, we run the addShip function again, which will move the enemy ship back to the right side of the stage so it can attack again. Then we’re checking to see if timer’s value is over 25, if it is, we assign dir a value of either 1 or 2 and reset timer back to zero. Depending on the value of dir, the enemy ship will either move up or down at the rate of 1 pixel per frame. Finally we add one to timer with timer++ at the end of the function. The two if statements at the end are what will make our enemy ships travel up or down but they won’t constantly switch back in forth, because the value of dir is random, it could be 1 four times in a row or it could constantly switch. This will give our enemies a little more life to them and make the game more interesting.
In Step 1, we made our ship move around the stage and in step 2 we’re going to make it fire lasers, which, of course, we need to destroy our enemies.
I’ve been rewriting a game I made in AS2 for school. Figuring out how to do somethings in AS3 is sometimes more difficult than you’d first think, but it’s also a great learning experience.
In AS2, one of the ways to build projects was to put the code directly on the movieclip, so in my AS2 version of the game, the laser’s code was in a frame on the actual movieclip. With AS3, you could do the same thing, but it’s not really the way we are supposed to do. The proper way is to make a separate ActionScript file for the laser. We should have the main code in a AS file but for now we’ll just concentrate on getting this to work.
To create the laser, use the Rectangle tool(R) and drag out a rectangle that would look like a laser your ship would shoot. Mine’s 32×5 and is red. You can make it whatever shape you want to fit your design. Now select it and press F8 or right click and Convert to Symbol. Call it Laser and make sure the registration point is the top left. Click the Export for ActionScript box and make sure it says “Laser”.
Now delete the laser from the stage, you’ll see that in your library the laser movieclip has “Export: Laser” beside it. This means that we can call the laser movieclip and add it to the stage through ActionScript, add it as many times as we want and also remove it.
Now we need to make the AS file that will tell the laser what to do. Go File > New > ActionScript File. Save the AS file in the same folder as your game’s .fla and call it “Laser”. It has to be named what you put in the Export for ActioScript field or else Flash won’t be able to find it. Now for the code. Because it’s an AS file and the code isn’t directly in the movie, there are a couple of different things we have to add.
Ok, what’s going on here? Because it’s an external AS file, it has to be put into a package. Next we have to import the classes that we want to use. Our public class Laser extends the class MovieClip which pretty much means we are taking all the attributes of the movieclip class and then adding our own stuff to it. For the most part, external classes extend MovieClip or Sprite. Next, every class has a main function which has the same name as the class.
Let’s head back to our main .fla where we have to add a few lines of code. First, at the top with the variables, add these:
1 2 3
vartimer:int = 0; var limit:int = 5; var allowFire:Boolean = true;
These are to control the rate of fire of our laser or else the player will just be able to hold down the fire button and fire continuously. The timer is our counter, we could use the Timer class that’s build into ActionScript, but it’s a lot simpler in this case to just use the frames of our movie to increase the counter. The limit variable is the number that timer has to be equal to or greater than in order to fire. And when timer is, in this case, over 5, we will set the variable allowFire to true and the player is able to fire again. In our moveRocket function, we have some code to add that will allow us to fire our laser. At the end of the function add:
The top part of the code is pretty simple, we are just checking is timer less than limit? If it is, timer++ or timer + 1. If timer is greater than limit, we are setting allowFire to true and resetting timer back to 0. The second part is where we add the laser to the stage. e.keyCode == 32 is checking to see if the spacebar has been pressed, as 32 = spacebar in ActionScript. If it has, it’s also checking to see if allowFire is true, if it isn’t, the ship can’t fire, if it is then it runs the code in the {}. First thing it does is set allowFire back to false, which restarts the timer. Next is the code that generates a new laser. Since we’ve created a class called Laser, it’s just like making a new MovieClip or Tween or Sprite. Now that we’ve created newLaser we give it it’s position newLaser.x is the same as rocket.x + half the width of the rocket and newLaser.y is exactly the same as rocket.y. Finally, we add newLaser to the stage with addChild(newLaser);
Now we go back to Laser.as and tell the laser how we want it to move. Below the public class line but above the public function add:
_root allows the Laser to know what’s going on on the stage and laserSpeed is how fast we want the laser to move. Private var means that we don’t want anything outside of this class accessing these variables, if we wanted to be able to modify them with other code, we would set them to public. Next, inside the Laser function add these two lines:
In this function, we are telling the laser to move 10 to the right everything frame and if it’s position is greater than 550, which is the width of my stage, it removes the event listener for moveLaser and then it removes itself from the stage.
A couple of days ago, a friend of mine asked for my help building a space shooter game in Flash. Not the most original choice, but he was doing it as an experiment and to learn more about Flash and ActionScript 3. Making a shooter game is one of the best ways to become familiar with ActionScript basics, it was the first time I used arrays outside of simple examples.
The problem that he was having was he wanted his ship to move fluidly and to be able to move diagonally. Being a giant geek, I can say I’ve made my fair share of space games in Flash, including a couple when I was in school. After looking at his code I saw immediately what he needed to do.
I’ve recreated what he made and also the changes that I made.
To move the ship around, we start off with this pretty simple code. We have a ship MovieClip on the stage with an instance name of rocket.
What is being used here is the KeyboardEvent. ActionScript looks for a key to be pressed and if it’s the right one, it does the assigned action. If you push the Up Arrow on your keyboard, which in ActionScript is key number 38, the ship will move up 10 pixels on the stage. Push the Down Arrow or key number 40 and you move down 10 pixels. 37 is Left and 39 is Right. This will get you this:
This isn’t too bad. The ship moves around pretty well but you can’t move diagonally and if you wanted to make a game with lots of enemies and bullets flying everywhere, moving like this is going to result in dying a lot! To get the effect we want, we are going to use booleans.
A boolean variable can only have one of two values, it’s either true or false. We can use this to see whether or not a key is being pressed and it will also allow us to check for more than one key at a time. We need to declare 4 variables, one for each direction.
Next we need to change our moveRocket function. We need to replace the rocket.y -= 10; with moveUp=true;. This will tell our game that when the Up Arrow key is press to change the moveUp variable to true. We make this change for each key:
If you tested the game now, nothing would happen because we still have to create the function to move the ship. This function is pretty much the same as what moveRocket use to be but instead of checking to see if a key has been pressed, it’s checking to see if a variable is true or false.
This is just the opposite of the moveRocket function. When you stop pressing the key, the variable switches back to false. We also need to add an EventListener for this function.
When I first started learning ActionScript 3.0, one thing I found was, unlike AS2, no one seemed to be putting up the basics of AS3. One of the first things I wanted to do was, of course, make a button. It took a lot of searching but I finally found a blog that just listed the changes that had been made to AS3 from AS2 and since I was pretty good with AS2, I figured it out on my own.