search

Make a Tower Defense Game in AS3: Aim and Fire

Hey Flash developers! In this tutorial series we are going to go through the process of developing a very basic Tower Defense game. In this first part of the series, we’ll learn how to deploy turrets on the game field, give them the ability to aim at an object (in this case, the mouse) and make them fire particles.


Final Result Preview

Once we complete this tutorial, we are going to have this:

Click a circle to mount a turret on it. Notice how all the turrets rotate so that they point towards the mouse cursor. Click, and all mounted turrets will fire a particle towards the cursor.


Step 1: What is a Tower Defense Game?

Wikipedia’s definition sums it up nicely:

The goal of tower defense games is to try to stop enemies from crossing a map by building towers which shoot at them as they pass.

That is essentially what we will be developing in this tutorial series. Remember that we refer to the towers as turrets in this tutorial.

Cursed Treasure is a great example of a TD game, if you’re still unsure.


Step 2: Setup – IDE

Before we start developing the game, we need to setup the project on our IDE. I’ll be using FlashDevelop here. If you want to read about how to setup the project on Flash Develop, please have a read Steps 1 and 2 of this tutorial, or this full guide to FlashDevelop.

So now you should have a main class, Main.as, with the following code:

package
{
	import flash.display.Sprite;

	public class Main extends Sprite
	{
		public function Main():void
		{
		}
	}
}

Step 3: Understand the Game Elements

For this part, our game will have following game elements:

  1. Game Field: The area where all game elements will be placed.
  2. Turret Placeholder: This is a place on the game field, defined to hold a turret.
  3. Turret: Our weapon in the game that can be placed on turret placeholders.
  4. Bullet: And finally, the particles that the turrets fire.

All the above elements will be created in the Main.as except the turrets which will be a separate Turret class.

Lets start coding now!


Step 4: Creating the Placeholders

First we’ll create a function called createTurretPlaceholder() which will create and return us a placeholder sprite. Add the following to the Main class:

private function createTurretPlaceholder():Sprite {
	var placeholder:Sprite = new Sprite();

	// draw the graphics
	var g:Graphics = placeholder.graphics;
	g.beginFill(0xCE7822);
	g.drawCircle(0, 0, 20);
	g.endFill();

	return placeholder;
}

This function is simply creating a Sprite variable placeholder. Then using Actionscript drawing API we create the graphic, which is a simple circle. Finally it returns that sprite.


Step 5: Adding Some Placeholders

Now we’ll create three placeholders using the previous function and put them at different positions on the field. Add the following code in the Main() constructor:

var placeholder1:Sprite = createTurretPlaceholder();

In the above statement we create a variable placeholder1 of type Sprite which receives a placeholder from the above createTurretPlaceholder() function.

placeholder1.x = 200; placeholder1.y = 60;

We position the placeholder on the field.

addChild(placeholder1);

And then we add the placeholder to the stage.

Using the same code, we’ll add two more placeholders to the field – so your Main() function should look like this:

public function Main() {
	var placeholder1:Sprite = createTurretPlaceholder();
	placeholder1.x = 200; placeholder1.y = 60;

	var placeholder2:Sprite = createTurretPlaceholder();
	placeholder2.x = 60; placeholder2.y = 260;

	var placeholder3:Sprite = createTurretPlaceholder();
	placeholder3.x = 350; placeholder3.y = 260;

	addChild(placeholder1);
	addChild(placeholder2);
	addChild(placeholder3);
}

Step 6: Turret – Creating the Class

As I mentioned before, the turret is going to be a separate class. This is because turrets need to have specific properties and methods of their own, and to be extended in future to create different type of turrets. This makes them a perfect candidate to be defined in a separate class.

Go on and create a new class called Turret, derived from Sprite, in a file named Turret.as. It should have the following basic code:

package
{
	import flash.display.Sprite;

	public class Turret extends Sprite
	{

		public function Turret()
		{
		}
	}
}

Step 7: Turret – The Graphics

Now that we have base structure of the Turret class, the next step is to give the turret some graphics. For that we create a new function called draw() in the class. So put the following function just below the constructor:

private function draw():void {
	var g:Graphics = this.graphics;
	g.beginFill(0xD7D700);
	g.drawCircle(0, 0, 20);
	g.beginFill(0x800000);
	g.drawRect(0, -5, 25, 10);
	g.endFill();
}

As you might have noticed in the code, we draw a circle and a rectangle on it. That’s how our turret is going to look. Now we call this function from the constructor itself.

public function Turret()
{
	draw();
}

Step 8: Creating a Ghost Turret

The next thing we do is to display a ghost turret when we hover the placeholders that we have put on the game field. What is a ghost turret? Well, its just a transparent turret that appears when hovering the mouse on the placeholders, to tell the player that a turret can be deployed there.

To begin with this, we need a ghost turret. Go ahead and declare a variable for it in the Main class.

private var ghost_turret:Turret;

Now create a new turret in the Main() constructor:

ghost_turret = new Turret();

Give the ghost turret some properties so that it looks like a ghost:

ghost_turret.alpha = 0.5;
ghost_turret.mouseEnabled = false;
ghost_turret.visible = false;

In the above code we lower down the opacity of the turret to half (0.5) and set the mouseEnabled property of the turret to false so that the ghost turret does not receive any mouse events. Why? We will see that later. And as the ghost turret will be invisible by default, we hide it.

Finally, add the turret to the display list:

addChild(ghost_turret);

Your Main constructor should look something like this:

public function Main() {
	var placeholder1:Sprite = createTurretPlaceholder();
	placeholder1.x = 200; placeholder1.y = 60;

	var placeholder2:Sprite = createTurretPlaceholder();
	placeholder2.x = 60; placeholder2.y = 260;

	var placeholder3:Sprite = createTurretPlaceholder();
	placeholder3.x = 350; placeholder3.y = 260;

	addChild(placeholder1);
	addChild(placeholder2);
	addChild(placeholder3);

	ghost_turret = new Turret();
	ghost_turret.alpha = 0.5;
	ghost_turret.mouseEnabled = false;
	ghost_turret.visible = false;

	addChild(ghost_turret);
}

If you run the movie now (Ctrl+Enter), all you’ll see is three placeholders on the stage. Boring huh? Lets add some interactivity.


Step 9: Showing/Hiding the Ghost Turret

We want the ghost turret to appear when the mouse hovers over any placeholder. So let’s attach mouse listeners to each placeholder in the createTurretPlaceholder() function just before it returns the placeholder variable.

private function createTurretPlaceholder():Sprite {
	var placeholder:Sprite = new Sprite();

	// draw the graphics
	var g:Graphics = placeholder.graphics;
	g.beginFill(0xCE7822);
	g.drawCircle(0, 0, 20);
	g.endFill();

	placeholder.addEventListener(MouseEvent.MOUSE_OVER, showGhostTurret, false, 0, true);
	placeholder.addEventListener(MouseEvent.MOUSE_OUT, hideGhostTurret, false, 0, true);
	return placeholder;
}

The code attaches listeners to MOUSE_OVER and MOUSE_OUT events.

Next we define the two handler functions for the same. Add the following two functions below the createTurretPlaceholder() function:

private function showGhostTurret(e:MouseEvent = null):void {
	var target_placeholder:Sprite = e.currentTarget as Sprite;
	ghost_turret.x = target_placeholder.x;
	ghost_turret.y = target_placeholder.y;
	ghost_turret.visible = true;
}		

private function hideGhostTurret(e:MouseEvent = null):void {
	ghost_turret.visible = false;
}

hideGhostTurret() just hides the ghost turret but whats going on in the showGhostTurret function? Lets see.

var target_placeholder:Sprite = e.currentTarget as Sprite;

We get the reference of the placeholder on which mouse is present using the MouseEvent‘s currentTarget property, typecasted to Sprite.

ghost_turret.x = target_placeholder.x;
ghost_turret.y = target_placeholder.y;
ghost_turret.visible = true;

This is simple…we position the ghost turret to the placeholder’s cordinates and make it visible. Run the movie and you should see the ghost turret appear when hovering over the placeholders. Nice!


Step 10: Deploying Turrets

Our next objective is to deploy a turret when a placeholder is clicked. For that we need a CLICK listener on the placeholder. But before that we need an Array variable which will hold all our turrets, so we can reference them at any time later. Make one in the Main class.

private var turrets:Array = [];

Then attach another listener just below the two previous listeners we added in the createTurretPlaceholder() function:

placeholder.addEventListener(MouseEvent.MOUSE_OVER, showGhostTurret, false, 0, true);
placeholder.addEventListener(MouseEvent.MOUSE_OUT, hideGhostTurret, false, 0, true);
placeholder.addEventListener(MouseEvent.CLICK, addTurret, false, 0, true);

Declare the addTurret() handler function below the hideGhostTurret() function:

private function addTurret(e:MouseEvent):void {
}

Now lets write the code for the function. Add the following code to the addTurret() function.

var target_placeholder:Sprite = e.currentTarget as Sprite;

We first get the reference to the placeholder that was clicked just like we did in the showGhostTurret() function.

var turret:Turret = new Turret();

The we create a new turret in a variable named turret.

turret.x = target_placeholder.x;
turret.y = target_placeholder.y;

Next, we position the turret at the coordinates of the target_placeholder.

addChild(turret);
turrets.push(turret);

When the turret is created, we add it to the stage and push it onto the array.

Your addTurret function should look like this in the end:

private function addTurret(e:MouseEvent):void {
	var target_placeholder:Sprite = e.currentTarget as Sprite;
	var turret:Turret = new Turret();
	turret.x = target_placeholder.x;
	turret.y = target_placeholder.y;
	addChild(turret);
	turrets.push(turret);
}

One thing to note here. Remember we set the mouseEnabled property of the ghost turret to false? If we hadn’t, the ghost turret in between the placeholder and mouse would have captured the click event, thus preventing the event from reaching the placeholder. As a result the CLICK listener attached to the placeholder would not have get called.

You might want to remove the CLICK listener from the placeholder. I haven’t done it here since the new turret blocks any clicks, but if you use a different turret design, it’s a good idea.

Well thats all we need to place our turrets. Try running the movie and you should be able to deploy turrets on placeholders.


Step 11: Making the Turret Move

For this tutorial we will make the turret rotate to face the mouse. We’ll keep the rotation functionality in a separate method of the Turret class. This method will be called update().

Lets add this method to Turret now:

public function update():void {
	var angle:Number = Math.atan2(stage.mouseY - this.y, stage.mouseX - this.x) / Math.PI * 180;
	this.rotation = angle;
}

All we do in ths function is calculate the angle of the mouse from the turret and set the turret’s angle to it. (Take a look at Trigonometry for Flash Developers if you’re not sure how this works.)

But notice that we have not called this function from anywhere and so nothing happens yet. This function will be called from the game loop that we define next. Lets go!


Step 12: The Game Loop

Whats a game loop? Its a function that is attach to the ENTER_FRAME event and so it gets called on every frame. It updates all the elements in the game…in our case, Turrets. More details in this article.

Create a function called gameLoop() below the Main() constructor which will be a listener to the ENTER_FRAME event of the movie:

private function gameLoop(e:Event):void {
}

Now that we have the listener function defined, we need to attach it to the corresponding event. We do so in the Main() constructor. Add the following line to the Main() function:

public function Main() {
	var placeholder1:Sprite = createTurretPlaceholder();
	placeholder1.x = 200; placeholder1.y = 60;

	var placeholder2:Sprite = createTurretPlaceholder();
	placeholder2.x = 60; placeholder2.y = 260;

	var placeholder3:Sprite = createTurretPlaceholder();
	placeholder3.x = 350; placeholder3.y = 260;

	addChild(placeholder1);
	addChild(placeholder2);
	addChild(placeholder3);

	ghost_turret = new Turret();
	ghost_turret.alpha = 0.5;
	ghost_turret.mouseEnabled = false;

	addChild(ghost_turret);
	stage.addEventListener(Event.ENTER_FRAME, gameLoop);
}

Step 13: Updating All the Turrets

Lets put some code in our gameLoop() function.

for each(var turret:Turret in turrets) {
}

We iterate over the turrets array, which has references to all turrets on the stage, using a for each...in loop.

for each(var turret:Turret in turrets) {
	turret.update();
}

And call the update() function of each turret. And we are done. If you run the movie now, you should be able to deploy turrets which always face the mouse. Something like this:


Step 14: Making the Turrets Shoot

Our next objective is to make the turrets shoot bullets. At whom? For this tutorial, we’ll make the turrets shoot towards any point we click on the stage. We’ll do this like so:

  1. Add a click listener to the stage.
  2. Iterate over all the turrets in the above listener.
  3. Calculate the angle from the clicked point to the turret.
  4. Create a new bullet and move it in the appropriate direction.

Lets declare the listener function named shoot Add the function to Main class:

private function shoot(e:MouseEvent):void {
}

And then attach the above listener to the CLICK event of stage in the Main() constructor:

stage.addEventListener(MouseEvent.CLICK, shoot);
stage.addEventListener(Event.ENTER_FRAME, gameLoop);
}

Step 15: Creating the Bullet

Before we proceed to writing the code for shooting in the shoot() function, we will define a new function for creating a bullet, just like we did for creating a placeholder. So put the following function below the createTurretPlaceholder():

private function createBullet():Sprite {
	var bullet:Sprite = new Sprite();
	// draw the graphics
	var g:Graphics = bullet.graphics;
	g.beginFill(0xEEEEEE);
	g.drawCircle(0, 0, 5);
	g.endFill();
	return bullet;
}

Nothing much here. We just create a new Sprite, draw an off-white color circle inside it, and return it. Now let’s continue to define our shoot() function.


Step 16: How to Shoot?

Time to add some code to the shoot().

for each(var turret:Turret in turrets) {
}

First, we iterate over all the turrets on the stage using the for each...in loop.

var new_bullet:Sprite = createBullet();

Now for every turret we create a bullet using the function we created previously.

new_bullet.rotation = turret.rotation;

Here we store the value of turret’s rotation property in bullet’s rotation. Why? Well…rotating the bullet is not what we want. The bullet needs to continue moving in direction determined by the turret, and for this we need the turret’s rotation value from the time it shot the bullet. We just store this as the bullet’s rotation for future use.

new_bullet.x = turret.x + Math.cos(new_bullet.rotation * Math.PI / 180) * 25;
new_bullet.y = turret.y + Math.sin(new_bullet.rotation * Math.PI / 180) * 25;

These two lines set the bullet’s initial position, which is 25 pixels away from the turret in the direction of facing (remember the rotation property). Again, read up on trigonometry if this is unfamiliar to you.

addChild(new_bullet);

And as the usual last step, we add the bullet to the stage’s display list.

This is how your shoot() function should look like:

private function shoot(e:MouseEvent):void {
	for each(var turret:Turret in turrets) {
		var new_bullet:Sprite = createBullet();
		new_bullet.rotation = turret.rotation;
		new_bullet.x = turret.x + Math.cos(new_bullet.rotation * Math.PI / 180) * 25;
		new_bullet.y = turret.y + Math.sin(new_bullet.rotation * Math.PI / 180) * 25;
		addChild(new_bullet);
	}
}

If you run you game now and click on any placeholder, the turret will get get deployed – but oops… we have a problem here. An extra bullet also gets created with the turret. Lets fix this.


Step 17: Why Did That Extra Bullet Appear?

To understand this we need to understand event propagation in AS3.

Any event which gets generated passes through three phases: capturing, target and bubbling. The events starts from the topmost parent of the target which generated the event. It passes through all the inner child elements, which is the capturing phase. Then it reaches the actual target which is the target phase. Then the event goes back to the top, passing through same elements in reverse, which is the bubbling phase. In the bubbling phase, all the elements which have a listener defined for the propagating event get triggered and their listeners are executed.

We have a CLICK listener bound to the stage and the placeholders. But the placeholders are also children of the stage. So when we click the placeholder, a CLICK event gets generated with the target as the placeholder. The event propagates from the stage towards the placeholder – the capture phase. It reaches the placeholder and its CLICK handler, the addTurret() function, gets executed and we have a turret on the stage. Now the event propagates backwards – the bubbling phase – and when it reaches the stage again it finds a CLICK listener for it as well, which gets executed. As a result the shoot() function gets executed and a bullet is added to the stage.

So thats the problem, but how to solve it? What we need to do is stop the event’s further propagation when it reaches the target. That means in the addTurret() we stop the event’s propagation. So go ahead and add a line at the end of addTurret():

private function addTurret(e:MouseEvent):void {
	var target_placeholder:Sprite = e.currentTarget as Sprite;
	var turret:Turret = new Turret();
	turret.x = target_placeholder.x;
	turret.y = target_placeholder.y;
	addChild(turret);
	turrets.push(turret);
	e.stopPropagation();
}

The line we added stops the event’s propagation and it doesn’t reaches the stage. For a more comprehensive understanding of event framework in Actionscript 3.0 read the AS3 101 post. Let’s continue with the game.


Step 18: Making the Bullet Move

We create the bullet on clicking the stage but it doesn’t move still. Our next step is to add an event listener to the bullet which gets called on every frame and moves it. First, we declare a variable for the bullet’s speed. Add the variable where the other variables are declared:

private var ghost_turret:Turret;
private var turrets:Array = [];
private var bullet_speed:uint = 3;

Then, add the following listener function to the Main class:

private function moveBullet(e:Event):void {
	var bullet:Sprite = e.currentTarget as Sprite;
	bullet.x += Math.cos(bullet.rotation * Math.PI / 180) * bullet_speed;
	bullet.y += Math.sin(bullet.rotation * Math.PI / 180) * bullet_speed;
}

What we do in this listener is:

  • Get the reference of the bullet whose listener was triggered.
  • Increment the bullet’s position by bullet_speed amount in the direction of the bullet’s rotation.

Lastly, attach the listener we just created to the ENTER_FRAME event of the bullet in the shoot() function:

private function shoot(e:MouseEvent):void {
	for each(var turret:Turret in turrets) {
		var new_bullet:Sprite = createBullet();
		new_bullet.rotation = turret.rotation;
		new_bullet.x = turret.x + Math.cos(new_bullet.rotation * Math.PI / 180) * 25;
		new_bullet.y = turret.y + Math.sin(new_bullet.rotation * Math.PI / 180) * 25;
		new_bullet.addEventListener(Event.ENTER_FRAME, moveBullet, false, 0, true);
		addChild(new_bullet);
	}
}

If you test you game now, you should see bullets moving when you click on the stage. But if you look carefully, you will notice that the bullets keep moving once created…even after they go out of the visible stage area. Our next step is to destroy the bullets as soon as they leave the movie boundaries.


Step 19: Destroying the Bullets

Add the following code in the end of moveBullet() function:

private function moveBullet(e:Event):void {
	var bullet:Sprite = e.currentTarget as Sprite;
	bullet.x += Math.cos(bullet.rotation * Math.PI / 180) * bullet_speed;
	bullet.y += Math.sin(bullet.rotation * Math.PI / 180) * bullet_speed;

	if (bullet.x < 0 || bullet.x > stage.stageWidth || bullet.y < 0 || bullet.y > stage.stageHeight) {
		bullet.removeEventListener(Event.ENTER_FRAME, moveBullet);
		bullet.parent.removeChild(bullet);
		bullet = null;
	}
}

Here we check whether the bullet is out of the stage boundaries. If it is, we remove its ENTER_FRAME listener and remove the actual bullet from the stage. We also set the bullet variable to null so that the bullet has no reference left and is available for garbage collection.


Conclusion

We have completed our basic tower defense game in which you can deploy turrets on specific placeholders which shoot towards any point we click on the stage. Cool, huh?

In the next part we’ll add enemies to the game and intelligence to the turrets so that they can do what they are suppose to do: defend. Also we’ll add some more elements that make the game look more complete and cool. Till then, try adding some more features to this on your own.



View full post on Activetuts+

Create a Pong Game in HTML5 With EaselJS – Tuts+ Premium

It’s Premium tutorial time! This week, Tuts+ members will learn how to use the EaselJS JavaScript library (along with SoundJS and TweenJS) to create a version of the classic Pong game in HTML5.


Premium Preview

HTML5 EaselJS Pong game tutorial
Click to play the demo

In this tutorial, we’ll create a clone of the classic game, Pong, in HTML5, using the EaselJS library. The game will have multiple screens, sound effects, and a (very simple) AI opponent.


Read the Full Tutorial

Premium members can access the full tutorial right away!

If you’re not yet a Premium member, you can still read the first few steps of the tutorial.


Tuts+ Premium Membership

We run a Premium membership system which periodically gives members access to extra tutorials, like this one! You’ll also get access to Psd Premium, Vector Premium, Audio Premium, Net Premium, Ae Premium, Cg Premium, Photo Premium, and the new Mobile Premium too. If you’re a Premium member, you can log in and download the tutorial. If you’re not a member, you can of course join today!

Also, don’t forget to follow @envatoactive on twitter, circle us on Google+, like us on Facebook, and grab the Activetuts+ RSS Feed to stay up to date with the latest tutorials and articles.



View full post on Activetuts+

Build an Active Flash Game Menu: Slides

Stop using static menus! Most players immediately base their initial impression of a Flash game on the menu that they see when they load it. Stand out from the crowd with an active menu!

This tutorial was first posted in December 2011, but has since been updated with extra steps that explain how to make the code more flexible!


Final Result Preview

Introduction: Static vs Active

The word “static” essentially means lacking in change. The majority of menus we see throughout web games are lacking in change, you simply press Play and the game starts. Menus like that are overused and show little creativity or innovation.

To make a menu “active” we must continuously cause change. So in this tutorial that is exactly what we are going to accomplish: a menu that continuously changes.


Step 1: Setting Up

The first thing we are going to need to create is a new Flash File (ActionScript 3.0). Set its width to 650px, its height to 350px, and the frames per second to 30. The background color can be left as white.

Now save the file; you can name it whatever you please, but I named mine menuSlides.fla.

In the next section we will create the nine MovieClips used in the menu. For reference, here is a list of all the colors used throughout the tutorial:

  • White – #FFFFFF
  • Gold – #E8A317
  • Light Gold – #FBB917
  • Blue – #1569C7
  • Light Blue – #1389FF
  • Green – #347235
  • Light Green – #3E8F1B
  • Red – #990000
  • Light Red – #C10202
  • Matte Grey – #222222

Step 2: Creating the Slide MovieClips

To start with we will create the slides used in the transitions, but before we begin let’s turn on some very useful Flash features.

Right-Click the stage and select Grid > Show Grid. By default it will create a 10px by 10px grid across the stage. Next, right-click the stage again and this time select Snapping > Snap to Grid.

Now we can begin drawing! Select the Rectangle Tool and draw a Light Gold rectangle, 650px wide and 350px tall (you can Alt-click on the stage to make this easier). Now change the color to Gold and draw groups of three squares, each 20x20px, to form the shape of an L in each corner,:

The basic Slide Design

Select the whole stage, right-click and choose Convert to Symbol. Name the MovieClip goldSlide and make sure that the type is MovieClip and the registration is top-left.

To save time and make things a whole lot easier, right-click the goldSlide MovieClip in the Library and select Duplicate Symbol three times to make three more copies. Change the colors in the new MovieClips to blue, green and red, then rename the MovieClips to blueSlide, greenSlide and redSlide.

Before we continue we should add some text to each slide. On goldSlide write PLAY, on blueSlide write INSTRUCTIONS, on greenSlide write OPTIONS and on redSlide write CREDITS.

Now that we have the text in place we can break it apart by right-clicking on it and selecting Break Apart twice; this will break the text down to a fill which will transition more smoothly. Plus as a bonus there will be no need to embed a font if you are just using it for the menu!

The Buttons

Now that we have drawn the 4 slides we can focus on the sideButton MovieClip that is used to move the slides either left or right.

First, draw a rectangle 30x60px with only a stroke (no fill), then draw diagonal lines 45 degrees from the top-right and bottom-right corners until they snap together in the middle of the opposite side. Now apply a Matte Grey fill to the triangle:

What your side Button Should Look Like

Next, delete the lines, then right-click the triangle and select Convert to Symbol. Name it sideButton, set the type to Button and make sure the registration is in the top-left corner.

Now insert 3 keyframes in the timeline by right-clicking the timeline and selecting Insert Keyframe. On the Up frame, select the fill of the triangle, go to the Windows tab and select Color. Change the Alpha to 50%. On the Over Frame repeat the same process, but this time set the alpha to 75%.

Now we can begin on the four numbered circle buttons, for jumping directly to a particular slide.

To start draw a white 30px circle with no stroke. Convert it to a symbol, name it circleOne, and set its type to Button and its registration point to the center. Insert three keyframes like we did before and then go to the Up frame.

Draw a black 25px circle with no stroke and center it to the middle through the coordinates or by using the Align menu. Next deselect the black circle, then reselect it and delete it. You should now have a white ring remaining. Now grab the text tool and put a white “1″ in the center of the ring. Then break this number apart until it is a fill.

circleOne Up Frame

Go to the Over frame and draw a black “1″. Center it and break it apart until it becomes a fill. Now deselect and reselect the fill, then delete it. Select everything on the frame and copy it, then go to the Down frame, select everything on it and hit delete. Paste in what we have copied.

circleOne Over Frame

Now create three more circle MovieClips, following the same process, for the numbers 2, 3 and 4.


Step 3: Positioning the MovieClips

Okay, we’re almost half-way done! First drag all of the slides onto the stage and position them with the following coordinates:

  • goldSlide: (0, 0)
  • blueSlide: (650, 0)
  • greenSlide: (1300, 0)
  • redSlide: (1950, 0)

Now drag and drop two copies of the sideButton. The first copy should be positioned at (10,145); before we can position the second copy we must first flip it!

Select the second copy and press Ctrl-T. Change the left-right to -100% and leave the up-down at 100%. Now move the second copy to (640,145).

Finally drag and drop the four circle MovieClips and position them as so:

  • circleOne: (30, 320)
  • circleTwo: (70, 320)
  • circleThree: (110, 320)
  • circleFour: (150, 320)

Your stage should now look like this:

What your stage Should Look Like

The blue, green and red slides are hidden just off to the right of the stage. Now select everything on the stage and convert to a symbol. Name it menuSlidesMC, set the type to MovieClip and the registration to the top-left corner, and export it for ActionScript as MenuSlidesMC.

Before we finish we must give each of the MovieClips inside menuSlidesMC an instance name. Select each slide in the order they appear from the left and name them slide1, slide2, slide3 and slide4 respectively. Name the circle buttons one, two, three and four, and finally name the side buttons left and right.


Step 4: Setting Up the Classes

Now that all of our MovieClips have been created we can start setting up the two classes we are going to use.

First go to your Flash file’s Properties and set its class to menuSlides; then, create a new ActionScript 3.0 file and save it as menuSlides.as.

Now copy the following code into it; I will explain it after:

package{
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;

	public class menuSlides extends MovieClip{
		public var menuSlidesMC:MenuSlidesMC = new MenuSlidesMC();
		public function menuSlides(){
			addChild(menuSlidesMC);
		}
	}
}

Pretty basic – it’s a document class, into which we imported the MovieClips and Events we will use. Then we created an instance of MenuSlidesMC, and added it to the stage.

Now create a new ActionScript 3.0 file for the menuSlidesMC instance. Save it as MenuSlidesMC.as and copy the following code into it:

package{
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;

	public class MenuSlidesMC extends MovieClip{
		public var speed:Number = new Number();
		public var activeSlide:Number = new Number();
		public function MenuSlidesMC(){
			speed = 10;
			activeSlide = 1;
			addEventListener(MouseEvent.CLICK, slidesClick);
			addEventListener(Event.ENTER_FRAME, slidesMove);
		}
	}
}

Just like last time, we imported what we are going to need, but we created two number variables. The first variable, speed, is actually how many pixels the slides are moved by each frame. (Note: this number has to evenly divide into your stage’s width to give a smooth transition). The second variable, activeSlide, tells us which slide is currently set to be on screen.

We also added two event listeners for functions we are going to create; one of them is called on a mouse click, and the other is called at the beginning of every frame.


Step 5: Creating the Event Handler Functions

To begin we will get the mouse click function out of the way. Start by creating a public function named slidesClick():

public function slidesClick(event:MouseEvent):void {

}

Next we will create some if-statements regarding the event.target.name. Basically, this property stores the name of the object that was targeted by the mouse click. We can use this to check which button is pressed:

if(event.target.name == "left"){
	if(activeSlide>1){
		activeSlide-=1;
	}
}else if(event.target.name == "right"){
	if(activeSlide<4){
		activeSlide+=1;
	}
}

if(event.target.name == "one"){
	activeSlide=1;
}else if(event.target.name == "two"){
	activeSlide=2;
}if(event.target.name == "three"){
	activeSlide=3;
}else if(event.target.name == "four"){
	activeSlide=4;
}

The code above goes in the slidesClick() function. The first set of if-statements are for the left and right side buttons; they increase or decrease the value of activeSlide, but never allow the value to become less than 1 or greater than 4 (since we only have four slides). The second set of if-statements are for the circle buttons; instead of just incrementing or decrementing the value of activeSlide they set it to the selected value.

Now let’s begin with the ENTER_FRAME handler function:

public function slidesMove(event:Event):void {

}

Add the slidesMove() function below your slidesClick() function and we’ll start adding some code to it. First, we’ll use a switch to check which slide should be on the screen, based on the value of activeSlide:

switch (activeSlide){
case 1:

break;
case 2:

break;
case 3:

break;
case 4:

break;
}

Now in each case we will create an if/else block that will check that slide’s current x-position, and move all of the slides either left, right, or not at all, depending on where the desired slide currently sits.

The first case looks like this:

if(slide1.x<0){
	slide1.x+=speed;
	slide2.x+=speed;
	slide3.x+=speed;
	slide4.x+=speed;
}else if(slide1.x>0){
	slide1.x-=speed;
	slide2.x-=speed;
	slide3.x-=speed;
	slide4.x-=speed;
}

Now all we have to do is repeat the same process for the other cases! After you are done your swtich should look like this:

switch (activeSlide){
	case 1:
		if(slide1.x<0){
			slide1.x+=speed;
			slide2.x+=speed;
			slide3.x+=speed;
			slide4.x+=speed;
		}else if(slide1.x>0){
			slide1.x-=speed;
			slide2.x-=speed;
			slide3.x-=speed;
			slide4.x-=speed;
		}
	break;
	case 2:
		if(slide2.x<0){
			slide1.x+=speed;
			slide2.x+=speed;
			slide3.x+=speed;
			slide4.x+=speed;
		}else if(slide2.x>0){
			slide1.x-=speed;
			slide2.x-=speed;
			slide3.x-=speed;
			slide4.x-=speed;
		}
	break;
	case 3:
		if(slide3.x<0){
			slide1.x+=speed;
			slide2.x+=speed;
			slide3.x+=speed;
			slide4.x+=speed;
		}else if(slide3.x>0){
			slide1.x-=speed;
			slide2.x-=speed;
			slide3.x-=speed;
			slide4.x-=speed;
		}
	break;
	case 4:
		if(slide4.x<0){
			slide1.x+=speed;
			slide2.x+=speed;
			slide3.x+=speed;
			slide4.x+=speed;
		}else if(slide4.x>0){
			slide1.x-=speed;
			slide2.x-=speed;
			slide3.x-=speed;
			slide4.x-=speed;
		}
	break;
}

And that’s it! We are all finished with the code and the menu should be working great right now.

…But wait, what if we want to add more slides or take some away?


Step 6: Adding Slides to an Array

At the moment our code isn’t very flexible due to all of those hard-coded if statements. So let’s do something bold: delete all of the code in the slidesMove() function because we will no longer be needing it, and also delete the if-statements for the circle buttons as we are going to optimize those as well.

Now declare a new variable (underneath speed and activeSlides):

public var slidesArray:Array = new Array();

The first variable, slidesArray, will be an array that contains all of our slides, which will allow us to access them by referencing an item in the array (so we can use slidesArray[2] instead of slide3).

One thing to note is that the first item in an array is given an index of 0, so we will have to make some changes to our instance names.

Select each slide in the order they appear from the left and name them slide0, slide1, slide2 and slide3, respectively. And to help us cut down on the number of lines of code we use, select each circle button in the order they appear from the left and name them circle0, circle1, circle2 and circle3, respectively.

If you are going to add more slides and buttons, now is the time to do so. Just position the extra slides at the end of the row of slides, then give them instance names following the same order. Then do the same for the circle buttons.

Now that we have the instance names correct we must add the slides to the array. Do so by adding the following code to your constructor:

slidesArray = [slide0, slide1, slide2, slide3, slide4, slide5];

Now the slides are in the array and can be accessed by their index in the array. For example, slidesArray[0] is equivalent to slide0 because that is the first item in the list.

Next, inside the “right” else-if statement, change the condition to:

if(activeSlide < slidesArray.length-1){

The value of slidesArray.length is equal to the number of elements in the array, so this new condition will now allow us to press the button and shift the slides over as long as the active slide is not the final slide.


Step 7: Handling Circle Button Presses

Now, when a circle button is clicked, we need to figure out which one it is (and which slide it refers to).

Create an array to hold all the circle buttons. First, define it, beneath the slide array:

		public var slidesArray:Array = new Array();
		public var circlesArray:Array = new Array();

Then, add the circle buttons to the array in the constructor:

			circlesArray = [circle0, circle1, circle2, circle3, circle4, circle5];

Now, move to the slidesClick() function, underneath the whole if-else block. We’re going to check whether the button clicked is in the circle buttons array:

			if (circlesArray.indexOf(event.target) != -1) {

			}

The array’s indexOf() function checks to see whether an object is in the array; if it’s not, it returns -1. So, we’re checking to see whether it’s not equal to -1, which will check to see whether it is in the array.

Assuming it is, then the indexOf() function will return the index of the button within the circle buttons array – so, if circle3 was clicked, circlesArray.indexOf(event.target) will be equal to 3. This means we can just set activeSlide to 3, and we’re done!

			if (circlesArray.indexOf(event.target) != -1) {
				activeSlide = circlesArray.indexOf(event.target);
			}

Step 8: Moving the Slides

The only thing left to do is move all of the slides. Begin by adding the same loop as we had before, in the slidesMove() function:

for(var i:int = 0; i < slidesArray.length; i++){

}

An if-else statement needs to be added now; this will use the variable activeSlide to select a slide out of the array and check where its x-position is, just like before.

if(slidesArray[activeSlide].x<0){

}else if(slidesArray[activeSlide].x>0){

}

Since activeSlide is a number, slidesArray[activeSlide] refers to one specific slide, so slidesArray[activeSlide].x is equal to that slide’s x-position.

In the first case we will add a for loop to move all of the movie clips to the right, and in the second case we will add a for loop to move all of the movie clips to the left.

Right:

for(var j:int = 0; j < slidesArray.length; j++){
	slidesArray[j].x+=speed;
}

Left:

for(var k:int = 0; k < slidesArray.length; k++){
	slidesArray[k].x-=speed;
}

If you test this now, you will notice that our optimised code has lead to a much zippier interface!


Step 9: Taking It Further

If you wanted to take this even further, you could use a for loop to position the slides and the circles, rather than needing to drag and drop them in the Flash IDE. For example, to position the slides, we’d first position slide0 in the constructor:

			slidesArray = [slide0, slide1, slide2, slide3, slide4, slide5];
			slidesArray[0].x = 0;
			slidesArray[0].y = 0;

Then, we’d loop through all the other slides, starting at slide1:

			slidesArray = [slide0, slide1, slide2, slide3, slide4, slide5];
			slidesArray[0].x = 0;
			slidesArray[0].y = 0;
			for (var i:int = 1; i < slidesArray.length; i++) {

			}

We can give all the slides an y-position of 0:

			slidesArray = [slide0, slide1, slide2, slide3, slide4, slide5];
			slidesArray[0].x = 0;
			slidesArray[0].y = 0;
			for (var i:int = 1; i < slidesArray.length; i++) {
				slidesArray[i].y = 0;
			}

…and then we can set each slide’s x-position to be 620px to the right of the slide before it:

			slidesArray = [slide0, slide1, slide2, slide3, slide4, slide5];
			slidesArray[0].x = 0;
			slidesArray[0].y = 0;
			for (var i:int = 1; i < slidesArray.length; i++) {
				slidesArray[i].x = slidesArray[i-1].x + 620;
				slidesArray[i].y = 0;
			}

If your slides aren’t 620px wide, you can even detect their width automatically!

			slidesArray = [slide0, slide1, slide2, slide3, slide4, slide5];
			slidesArray[0].x = 0;
			slidesArray[0].y = 0;
			for (var i:int = 1; i < slidesArray.length; i++) {
				slidesArray[i].x = slidesArray[i-1].x + slidesArray[i-1].width;
				slidesArray[i].y = 0;
			}

You can do the same thing with the circle buttons, but I’ll leave that up to you to experiment with.

The great thing about this is, you can add as many slides as you want to the menu; all you have to do is add them to the array, and they’ll be dealt with by this code.

(You can remove slides from the array, too, but they won’t be affected by any of the code, so you’ll probably need to reposition them in the Flash IDE.)

Conclusion

Thank you for taking the time to read through the tutorial, I hope it was helpful and that you learned a little something about active game menus.



View full post on Activetuts+

Create a Microphone-Controlled Flash Game: Code

This entry is part 2 of 2 in the series Create a Microphone-Controlled Flash Game

In this mini-series, we’re creating a spaceship game where the main control is via the microphone: shout louder to make the ship fly higher. So far, we’ve created all the required graphical elements for the game. Now, it’s time to work on our code. We’ve got a lot to do, so let’s get started!


Final Result Preview

For the purposes of keeping the tutorial simple, we have done no error checking for the existence of a microphone. This means that, if you do not have a microphone plugged in, turned on, and set up for use with Flash, the game won’t work: you’ll get an Error #1009. Check the comments in Player.as in the source files for information on how to deal with this.


A Small Note:

For some reason Flash Builder isn’t working perfectly. In particular, it’s ignoring code hinting – but, nevertheless, one should be able to follow the tutorial.


Project Setup

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!


Creating the Player

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!


Creating Space Objects

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!


Player Animation and Collision Response

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!


Setting Up Scores and Lives

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!


Creating Our Background

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!


Cleaning Up Our Game

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!


Creating the Game Over Screen

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!


Conclusion

Thank you for watching. It’s been a huge tutorial, and afterwards I would have liked to do some things differently:

  • First off the classes have just been added one by one, but it would have made more sense for the classes to be organised in packages.
  • Even though our project works fine, we do get some run time errors, which isn’t very neat.
  • Also, it’s pretty easy to get very far by saying nothing, and just sticking to the bottom of the screen.

Nevertheless, I hope you enjoyed this tutorial, and most importantly learned something from it.



View full post on Activetuts+

Weekend Lecture: Egoraptor Discusses Megaman’s Game Design

Interested in game design? This weekend, we feature an interesting look at game design in the NES game Megaman and its SNES sequel Megaman X, through a video by Egoraptor.


Watch the Video

Many games, particularly modern games aimed at a more casual audience, rely on tutorial missions and popups to teach you how to play the game; a few years ago, it was more common for games to be packed with a thick manual that explained all the controls and objectives. But there is a third option: letting the player learn through actually playing the game.

In this video, Egoraptor examines how Megaman did a great job of teaching through gameplay, and how Megaman X refined this even further.

Warning: there’s a lot of profanity in this, so it might not be safe for work.

Hat tip to Jesse Freeman for posting a link to this video on Google+!

If you’re interested in this subject, and would like to learn how to apply these lessons to app design, take a look at Dan Cook’s presentation, The Princess Rescuing Application.



View full post on Activetuts+

Page 1 of 1712345...10...Last »
top