AS3 Avoider Game Tutorial, Part 4: Menus and Buttons

by Michael James Williams on October 12, 2008 · 289 comments

in Avoider Game Base,Tutorial

(This tutorial is also available in Spanish)

Introduction

In this part of my AS3 conversion of Frozen Haddock’s avoiding game tutorial, we’ll be inserting a button to let the player restart the game if they die, and adding a menu screen to the start of the game.

Click the image below to see how this will look.

screenshot

If you’ve not been following the tutorial so far, grab the zip file of the game so far here and extract it somewhere. Otherwise, copy the files you’ve been working on so far to a new folder, as usual. Open the FLA file, and let’s get started.

Let Me Try That Again

At the minute, if the player touches an enemy, he’s sent to the game over screen and has to refresh the page in order to play again. We’re going to add a simple button to this screen that lets the player try again.

Create a new symbol of type Button (Insert > New Symbol, and select the Button option). Call it RestartButton, and click OK.

screenshot

You’ll enter editing mode for this new button. Draw whatever you like, as long as it’s obvious that clicking this will start the game again. Here’s mine:

screenshot

Now check out the timeline at the top of the screen:

screenshot

A button actually contains four separate images:

  • Up — What the button looks like normally.
  • Over — What the button looks like when the mouse is pointing at it.
  • Down — What the button looks like when it’s being clicked.
  • Hit — The area of the button that is “sensitive” to the mouse (more on this in a bit).

The shaded grey box with a dot in it in the Up column indicates that we have drawn an image for that state. Let’s draw images for the others now. Right-click each of the empty boxes in turn and select Insert Keyframe:

screenshot

screenshot

screenshot

OK, great. Click the shaded grey box with a dot in it (also known as a keyframe) in the Over column. It should have copied the image from the Up column into it; if not, you can copy and paste it from that column. Change the image in some suitable way — I’m just going to invert the colours of mine:

screenshot

Now change the Down keyframe in some other way:

screenshot

The Hit keyframe is a little different. The shape you draw in here defines the “clickable” area of the button. The player will never actually see this image. If you drew a button with a shadow, for instance, and you wanted the player to be able to click the button but not the shadow, then you would just draw the button’s shape in here and leave the shadowed area blank. (Does that make sense?)

Anyway, for my button I don’t want to leave any of the button unclickable, so I’m going to make the shape the same shape as the button:

screenshot

I’ve coloured it bright red just to remind myself that this is not going to be seen by the player, but you can make it any colour you like. You can even leave the original image there, if you want.

Now we need to add this button to the game over screen. Save what you’ve done, then double-click the GameOverScreen in the Library.

screenshot

Find your new RestartButton in the Library and drag it onto the game over screen.

screenshot

(Oops. I forgot that the black border of the button wouldn’t show up against the black background of the game over screen. Oh well.)

Remember back in the first part of this tutorial, when I talked about instances and classes? Well, the button on the game over screen is an instance of the class RestartButton. Since we haven’t defined it in ActionScript, it doesn’t have an instance name. If we want to be able to access it with code (and we do), we need to give it one.

Click the button you just added, and check out the Properties panel:

screenshot

The box marked is what we need. Enter restartButton (as usual, be careful with the capital letters!)

screenshot

All right, now we can write some code to get it to actually do something when it’s clicked.

Hey! …Listen!

So far we’ve used event listeners to trigger a function on the death of the avatar and the “tick” of the game timer. Now we’re going to be listening for the “click” of the restart button.

Since the button exists in the GameOverScreen, code concerning it must go in the GameOverScreen class. But… we never actually made such a class. So let’s do it now! Create a new AS file and enter the following:

?View Code ACTIONSCRIPT3
1
2
3
4
5
6
7
8
9
10
11
package 
{
	import flash.display.MovieClip;
	public class GameOverScreen extends MovieClip 
	{
		public function GameOverScreen() 
		{
 
		}
	}
}

Save this as GameOverScreen.as in your Classes directory.

Hopefully this code is looking quite familiar by now. Save everything and test the game. It’ll give you an error:

GameOverScreen.as, Line 2 1046:  Type was not found or was not a compile-time constant: SimpleButton.

What? Flash has detected that there is a button on the GameOverScreen but is saying “what is this? I have never heard of this ‘button’”. Flash can be pretty dumb sometimes.

We need to tell Flash exactly what a button is. Go back to GameOverScreen.as and modify it to import the SimpleButton class definition (line 4):

?View Code ACTIONSCRIPT3
1
2
3
4
5
6
7
8
9
10
11
12
13
package 
{
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
 
	public class GameOverScreen extends MovieClip 
	{
		public function GameOverScreen() 
		{
 
		}
	}
}

Now you can save it and test it. You’ll notice that the button changes when you hover over it and when you click it. Obviously it doesn’t actually do anything because we haven’t added the event listener yet. So let’s do that next.

Since this code is so similar to what we’ve added in earlier parts, I’ll just insert all of it at once and explain it afterwards:

?View Code ACTIONSCRIPT3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package 
{
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
	import flash.events.MouseEvent;
 
	public class GameOverScreen extends MovieClip 
	{
		public function GameOverScreen() 
		{
			restartButton.addEventListener( MouseEvent.CLICK, onClickRestart );
		}
 
		public function onClickRestart( mouseEvent:MouseEvent ):void 
		{
 
		}
	}
}
  • public function onClickRestart( mouseEvent:MouseEvent ) — This is the function that we want to be run upon clicking restart (hence, “on click restart”). Just as before, we are allowing information about the event (of the clicking) to be passed to this function.
  • restartButton.addEventListener( MouseEvent.CLICK, onClickRestart ); — This adds the event listener to the button, and tells it that if the button is CLICKed (yes, Flash really requires you to write CLICK in capitals like that) then it should run the onClickRestart function.
  • import flash.events.MouseEvent; — Without this line, Flash wouldn’t know what a mouse event was, which means it wouldn’t know the meaning of the word CLICK.

To start the game again, we have to remove the game over screen and reload the play screen. In Part 3 we rearranged everything so that the document class handled all this screen manipulation, so it’s that class that we need to modify. Open DocumentClass.as and add this new function:

?View Code ACTIONSCRIPT3
24
25
26
27
28
29
30
31
public function restartGame():void
{
	playScreen = new AvoiderGame();
	playScreen.addEventListener( AvatarEvent.DEAD, onAvatarDeath );
	addChild( playScreen );
 
	gameOverScreen = null;
}

Lines 26 & 27 set up the playScreen in exactly the same way as the constructor. This is necessary, because when the player gets Game Over, that line playScreen = null will erase the event listener and reset the x and y coordinates of the playScreen, as I explained in Part 3.

Line 30 would erase the gameOverScreen, but there’s a problem. gameOverScreen is only defined in the onAvatarDeath() function, so it isn’t available to the restartGame() function. Let’s make gameOverScreen available to the whole document class, just like playScreen:

?View Code ACTIONSCRIPT3
1
2
3
4
5
6
7
package 
{
	import flash.display.MovieClip;
	public class DocumentClass extends MovieClip 
	{
		public var playScreen:AvoiderGame;
		public var gameOverScreen:GameOverScreen;

Now we need to remove the var from the var gameOverScreen statement from onAvatarDeath, since we’ve already defined it:

?View Code ACTIONSCRIPT3
16
17
18
19
20
21
22
23
24
public function onAvatarDeath( avatarEvent:AvatarEvent ):void
{
	gameOverScreen = new GameOverScreen();
	gameOverScreen.x = 0;
	gameOverScreen.y = 0;
	addChild( gameOverScreen );
 
	playScreen = null;
}

Here’s what my class looks like:

?View Code ACTIONSCRIPT3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package 
{
	import flash.display.MovieClip;
	public class DocumentClass extends MovieClip 
	{
		public var playScreen:AvoiderGame;
		public var gameOverScreen:GameOverScreen;
 
		public function DocumentClass() 
		{
			playScreen = new AvoiderGame();
			playScreen.addEventListener( AvatarEvent.DEAD, onAvatarDeath );
			playScreen.x = 0;
			playScreen.y = 0;
			addChild( playScreen );
		}
 
		public function onAvatarDeath( avatarEvent:AvatarEvent ):void
		{
			gameOverScreen = new GameOverScreen();
			gameOverScreen.x = 0;
			gameOverScreen.y = 0;
			addChild( gameOverScreen );
 
			playScreen = null;
		}
 
		public function restartGame():void
		{
			playScreen = new AvoiderGame();
			playScreen.addEventListener( AvatarEvent.DEAD, onAvatarDeath );
			playScreen.x = 0;
			playScreen.y = 0;
			addChild( playScreen );
 
			gameOverScreen = null;
		}
	}
}

I’ve added lines 13 & 14 to position the playScreen at (0,0), just like with the gameOverScreen, and duplicated them in restartGame(). In a later part, I’ll simplify the way things work so that we don’t have to write the same code twice all the time.

REBOOT!

So now we have a function in gameOverScreen that is run when the restart button is clicked, and a function in the document class that restarts the game. It’s certainly tempting to hook the two together directly, but as I explained in the previous part, that leads to problems down the line. We’ll take the same approach here as we did with the avatar’s death: creating a new custom event.

What’ll happen is this:

  • Player clicks restart button
  • Restart button sends off a MouseEvent of type CLICK
  • MouseEvent.CLICK is picked up by an event listener within gameOverScreen, and triggers onClickRestart()
  • onClickRestart(), in turn, sends off our new custom event — let’s call it NavigationEvent — of type RESTART
  • NavigationEvent.RESTART is picked up by an event listener within the document class, and triggers a new function: onRequestRestart()
  • onRequestRestart() runs the restartGame() function

Phew! It’s long, but it’s actually quite straightforward. It also gives us scope for letting the player restart the game in other ways: when they press “R”, perhaps, or after a few seconds have passed. In either case, we just need to fire off a NavigationEvent.RESTART event, and we’ll already have done the rest.

Our new custom event looks much like the AvatarEvent:

?View Code ACTIONSCRIPT3
1
2
3
4
5
6
7
8
9
10
11
12
13
package  
{
	import flash.events.Event;
	public class NavigationEvent extends Event 
	{
		public static const RESTART:String = "restart";
 
		public function NavigationEvent( type:String )
		{
			super( type );
		}
	}
}

(Save this as NavigationEvent.as in the Classes folder.) Firing off the event is simple, too (this next bit goes in GameOverScreen):

?View Code ACTIONSCRIPT3
14
15
16
17
public function onClickRestart( mouseEvent:MouseEvent ):void
{
	dispatchEvent( new NavigationEvent( NavigationEvent.RESTART ) );
}

And with this being your third event listener, you should have no problems adding it to the document class (line 21):

?View Code ACTIONSCRIPT3
18
19
20
21
22
23
24
25
26
27
public function onAvatarDeath( avatarEvent:AvatarEvent ):void
{
	gameOverScreen = new GameOverScreen();
	gameOverScreen.addEventListener( NavigationEvent.RESTART, onRequestRestart );
	gameOverScreen.x = 0;
	gameOverScreen.y = 0;
	addChild( gameOverScreen );
 
	playScreen = null;
}

Of course, you need to create the onRequestRestart() function within the document class, and tell it what to do:

?View Code ACTIONSCRIPT3
29
30
31
32
public function onRequestRestart( navigationEvent:NavigationEvent ):void
{
	restartGame();
}

So now when the restart button is pressed (and after a long chain of events), the document class’s restartGame function will be run, which in turn will remove the game over screen and reload the play screen. Save it and test it, and at last, the player can restart the game without refreshing the page!

Hobson’s Choice

Adding a menu to the start of the game really isn’t difficult now. The code is going to be practically the same as for the game over screen. Let’s go through the steps real fast.

First, create a menu screen. You can create one from scratch if you like, but since the game over screen is already the right size I’m going to make a copy of that to start from.

Go back to your FLA file and find GameOverScreen in the Library. Right-click it and select Duplicate. It’ll ask for a name, so type in MenuScreen; leave the Type as Movie Clip. Double click the new MenuScreen in the Library to enter editing mode, and delete the restart button. Make whatever changes you want to the interface. Here’s mine:

screenshot

A true work of art.

Now for the button. Again, you can make one from scratch like we did earlier (remember it needs to be of type Button!), or you can duplicate the existing RestartButton. Totally your choice. Either way, call the new button StartButton and edit it accordingly. Here’s mine:

screenshot

I’m not being lazy, I’m maintaining a consistent style throughout my application. Add this new button to your MenuScreen and set the instance name to startButton.

screenshot

Now let’s write the code. Right-click the MenuScreen and select Properties. Check the Export for ActionScript box, enter MenuScreen in the Class box if it doesn’t come up automatically, and click OK. As usual, it’ll tell you:

screenshot

…so let’s create that class file.

Hit File > New and select ActionScript file. This is going to be the class file for our MenuScreen. Here’s the code:

?View Code ACTIONSCRIPT3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package 
{
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
	import flash.events.MouseEvent;
 
	public class MenuScreen extends MovieClip 
	{
		public function MenuScreen() 
		{
			startButton.addEventListener( MouseEvent.CLICK, onClickStart );
		}
 
		public function onClickStart( event:MouseEvent ):void
		{
			dispatchEvent( new NavigationEvent( NavigationEvent.START ) );
		}
	}
}

Save the file in your Classes directory as MenuScreen.as.

I’m not even going to explain most of this code, because it is almost exactly the same as GameOverScreen.as. Note, however, that in line 16 I’ve dispatched a NavigationEvent of type START — but at the minute the NavigationEvent class only has a RESTART type. Let’s add this new type to NavigationEvent.as right now:

?View Code ACTIONSCRIPT3
1
2
3
4
5
6
7
package  
{
	import flash.events.Event;
	public class NavigationEvent extends Event 
	{
		public static const RESTART:String = "restart";
		public static const START:String = "start";

Simple enough.

At the minute, the document class is displaying the play screen when it starts up. We’re going to change it to display our new menu screen instead. Change these lines:

?View Code ACTIONSCRIPT3
6
7
8
9
10
11
12
13
14
15
16
public var playScreen:AvoiderGame;
public var gameOverScreen:GameOverScreen;
 
public function DocumentClass() 
{
	playScreen = new AvoiderGame();
	playScreen.addEventListener( AvatarEvent.DEAD, onAvatarDeath );
	playScreen.x = 0;
	playScreen.y = 0;
	addChild( playScreen );
}

to this:

?View Code ACTIONSCRIPT3
6
7
8
9
10
11
12
13
14
15
16
17
public var menuScreen:MenuScreen;
public var playScreen:AvoiderGame;
public var gameOverScreen:GameOverScreen;
 
public function DocumentClass() 
{
	menuScreen = new MenuScreen();
	menuScreen.addEventListener( NavigationEvent.START, onRequestStart );
	menuScreen.x = 0;
	menuScreen.y = 0;
	addChild( menuScreen );
}

Note that I’ve added a new public var called menuScreen, and am no longer setting up the playScreen here.

Now we just need to make that new onRequestStart() function (line 13, above) and we’ll be sorted:

?View Code ACTIONSCRIPT3
35
36
37
38
39
40
41
42
43
44
public function onRequestStart( navigationEvent:NavigationEvent ):void
{
	playScreen = new AvoiderGame();
	playScreen.addEventListener( AvatarEvent.DEAD, onAvatarDeath );
	playScreen.x = 0;
	playScreen.y = 0;
	addChild( playScreen );
 
	menuScreen = null;
}

Save everything and test the game and… success!

Wrapping Up

I realise I went through things a bit faster in this part than I have previously. I’m doing this so as not to repeat myself, but if it’s just making things more confusing, please let me know.

As always, you can grab the zip file with everything I’ve done so far here, and you can subscribe to my RSS feed (to be alerted as soon as the next part is available) here.

In Part 5 I’ll show you how to add a clock and a score. Until then, why not have a go at adding a button to the Game Over screen that takes you back to the menu?

{ 288 comments… read them below or add one }

Steve September 6, 2011 at 9:15 pm

I gave a go at adding the button to return to the menu. The button is fully functional and returns me to the menu screen no problem. However, when I click the start button the menu screen, it doesn’t start the game again. Any ideas why this would happen?

ExplosionsHurt September 7, 2011 at 7:31 am

I’ve been making a game loosely based on this tutorial. It basically has a cannon in the middle of the screen which shoots rectangles at the player. These rectangles wrap around the screen.

For some reason, setting playScreen to null doesn’t seem to get rid of the rectangles. Instead, it seems to make the rectangles invisible, so that when I start playing the 2nd time there is often completely random game overs.

I can get past this by using removeChild() but when I do I get a lot of errors in the output box…

Any help?

kamal September 16, 2011 at 4:31 pm

TypeError: Error #2007: Parameter child must be non-null.
at flash.display::DisplayObjectContainer/addChild()
at AvoiderGame/moveEnemyAndAvatar()
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()

i got this error what’s worng you maybe know? :)

jon September 29, 2011 at 5:56 am

***created a movieclip symbol ‘InstructionScreen’ for screen – exported to actionscript

***duplicated start button, saved as ‘InstructionButton’, exported to actionscript

***added ‘InstructionButton’ to MenuScreen, instance name ‘instructionButton’

***added

 
public static const INSTRUCTION:String = "instruction";

to NavigationEvent.as

***added

 
public var instructionButton:InstructionButton;
 
public function InstructionScreen() 
        {
            instructionButton.addEventListener( MouseEvent.CLICK, onClickInstruction );
        }

    public function onClickInstruction( event:MouseEvent ):void
    {
        dispatchEvent( new NavigationEvent( NavigationEvent.INSTRUCTION ) );
    }

to MenuScreen.as

***added

 
public var instructionScreen:InstructionScreen;
 
public function showInstructionScreen():void
{
    instructionScreen = new InstructionScreen();
    instructionScreen.addEventListener( NavigationEvent.INSTRUCTION, onRequestInstruction, false, 0, true );
    instructionScreen.x = 0;
    instructionScreen.y = 0;
    addChild( instructionScreen );
}

public function onRequestInstruction( navigationEvent:NavigationEvent ):void
{
instructionScreen = new InstructionScreen();
instructionScreen.addEventListener( NavigationEvent.INSTRUCTION, onRequestInstruction, false, 0, true );

instructionScreen.x = 0;
instructionScreen.y = 0;
addChild( instructionScreen );

removeChild( menuScreen );
menuScreen = null;

stage.focus = instructionScreen;
}

to document.as

I`m not getting any error messages, the instructions button is just not doing anything

-one thing I noticed, where ever it says NavigationEvent.START the START is blue, but wherever it says NavigationEvent.INSTRUCTION the INSTRUCTION is not blue.

any suggestions on what I am doing wrong would be greatly appreciated

jon September 29, 2011 at 5:58 am

ooops

sorry in the previous comment I didn t explain my problem.

I am trying to add a button linking to an ‘instructions’ screen on the menu screen.

Im not getting any errors - Im just not getting the screen

any help would be greatly appreciated

Tyler October 1, 2011 at 11:39 pm

i cannot get my start button, on my starting menu to play the game if i return to it after using the menu button(which takes me back to the menu) it no longer works, but the first time i use the button it does work.
- any ideas?

Tyler October 2, 2011 at 3:54 am

Never mind i fixed it

Bjerke November 23, 2011 at 1:14 pm

I’ve been makeing a game based of this tutorial, but i startet with ENTER_FRAME instead of TIMER, but after a while i got trubles with it. Now that i’ve changed over, i get this error:
TypeError: Error #1034: Type Coercion failed: cannot convert flash.events::Event@24d8cfd9 to flash.events.TimerEvent.
what to do :S

Bjerke November 23, 2011 at 1:16 pm

forget it, found it out :) had missed out on one of my ENTER_FRAME eventListeners

Pocodude January 10, 2012 at 11:05 pm

THANKKKK YOUUUUUUU this helped alot :D

JayBee January 12, 2012 at 8:56 pm

To answer Steve’s Setp 11 post. This will put you back to the startMenu screen. Why you would want to do that is confusing to me but this is how you do it.

 public function restartGame():void
     {
            menuScreen = new MenuScreen();
        menuScreen.addEventListener(NavigationEvent.START,onRequestStart );
        menuScreen.x = 0;
        menuScreen.y = 0;
        addChild( menuScreen );

        gameOverScreen = null;

}

alex January 15, 2012 at 5:47 am

Hey there. I think this was going great, but it suffered from the same thing almost every manual suffers. Suddenly it assumes to much or throw in a lot of stuff without a thorough explanation. I’m sure you don’t mean it that way and maybe it is just me, but the part I’m referring to is the “REBOOT” part. From that point I started finding that not even your number lines of the classes (and I used the same indentation and spaces as you) were not matching mine. I’m not complaining. I’m just saying this so if it is me that is wrong maybe I could get where I was wrong, and if anyone else feels the same you have the chance to enhance it. Up to this points its been awesome. Hope I can get this clarified as I feel this tutorial is great.
Thanks and hope no one get my intention in the wrong way. Just trying to make the most of this. See ya.

Michael James Williams January 20, 2012 at 12:40 am

Ah, sorry Alex. I’ve heard people say that before about this part; it seems to be the point where I suddenly rocketed off at a much higher speed :/

Could you give me an example of code that doesn’t match? Maybe then I can fix it.

Caio Faustino February 7, 2012 at 4:46 pm

You propably didn’t notice but the links to the “code so far” are wrong from here, we get link to part 3 again, and in part 5 we get the link to part 4.

Kevin February 23, 2012 at 2:32 am

Hey, I have got my restart button working (haven’t gotten to the menu screen though). However, my game suffers slow down from each additional restart. (this adds up to a crawl at about 5 restarts).

Its like the game is duplicating behind the scenes on restart, what should I be looking for in my code? (I’ve got both null functions in)

GeorgeMan March 3, 2012 at 2:00 pm

Hi there,
I followed every step till now, and the game was working fine, until I added the restartButton.addEventListener.
I keep getting a 1061 error: Call to a possibly undefined method addEventListener through a reference with static type Class. My code is exactly the same as yours…

I’m quite new to ActionScript 3. If it is of any importance, I’m using Flash Professional CS5.5

Thanx in advance.

GeorgeMan March 3, 2012 at 2:23 pm

I found it!!!
I really should have checked the old comments -.-
Well, thanx to Q Smith for his comment! :)

GeorgeMan March 8, 2012 at 7:20 pm

Hi Michael,
It’s me again. Well, I followed Q Smith’s instructions, and got a Start Button, a Restart Button, and an Instructions Button working. But now, I’m trying to make a button on the Instructions Screen to start the game there. I did the same as with the others, I don’t get any errors, but there just won’t appear that ******* button! I’m stuck at this button for 2 days :( Pleez help me!

Levi March 17, 2012 at 8:57 am

I’m getting pretty confused over this. I downloaded and looked at the NavigationEvent.as from the zip. There seems to be a whole bunch of code and techniques that isn’t even touched on in the tutorials… I’ve been going a bit bonkers, hitting the wall trying to dissect the meaning of this code. Am I just missing where it’s explained? Is there a mixup between the zip and the actual tutorial code? Thanks for helping! Here are some examples:

public function NavigationEvent( type:String, bubbles:Boolean = false, cancelable:Boolean = false ) 
        { 
            super( type, bubbles, cancelable );

    }

public override function clone():Event 
{ 
    return new NavigationEvent( type, bubbles, cancelable );
} 

public override function toString():String 
{ 
    return formatToString( "NavigationEvent", "type", "bubbles", "cancelable", "eventPhase" ); 
}

</pre

TWS March 23, 2012 at 7:36 am

I followed the tutorial as far as I can see, but when I run the application, the start button does not take me to the game. From what I traced, it looks like the Menu screen isn’t using its event listener and isn’t registering when I click Start. I am using Flash CS4.

TWS March 25, 2012 at 2:44 am

Never mind, it was just a capitalization error. Grr…

Avery April 27, 2012 at 3:48 pm

I’m a beginner when it comes to as3. I put in all the code like you did, but i got error 1061: Call to a possibly undefined method addEventListener through a reference with static type Class. I tried everything to fix it but can’t seem to figure it out.
Here is the code for the document class and menu screen class:

DocumentClass:
package
{
import flash.display.MovieClip;
import flash.events.*;

public class DocumentClass extends MovieClip
{
    public var playScreen:AvoiderGame;
    public var gameOverScreen:GameOverScreen;
    public var menuScreen:MenuScreen;

public function DocumentClass()
{
    menuScreen = new MenuScreen();
    menuScreen.addEventListener(NavigationEvent.START, onRequestStart);
    menuScreen.x=0;
    menuScreen.y=0;
    addChild(menuScreen);
}

public function onAvatarDeath(avatarEvent:AvatarEvent):void
{
    gameOverScreen=new GameOverScreen();
    gameOverScreen.addEventListener( NavigationEvent.START, onRequestRestart );
    gameOverScreen.x = 0;
    gameOverScreen.y = 0;
    addChild(gameOverScreen);

    playScreen=null;//resetting it. All event listeners are removed, all contained objects are erased, 
    //all functions don't to exist anymore.
}

public function onRequestStart( navigationEvent:NavigationEvent ):void
{
    playScreen = new AvoiderGame();
    playScreen.addEventListener( AvatarEvent.DEAD, onAvatarDeath );
    playScreen.x = 0;
    playScreen.y = 0;
    addChild( playScreen );

    menuScreen = null;
}

public function onRequestRestart(navigationEvent:NavigationEvent):void
{
    restartGame();
}

public function restartGame():void
{
    playScreen=new AvoiderGame();
    playScreen.addEventListener(AvatarEvent.DEAD, onAvatarDeath);
    playScreen.x=0;
    playScreen.y=0;
    addChild(playScreen);

    gameOverScreen = null;
}

}

}

MenuScreen:
package
{
import flash.display.MovieClip;
import flash.display.SimpleButton;
import flash.events.MouseEvent;

public class MenuScreen extends MovieClip
{
    public function MenuScreen()
    {
        startButton.addEventListener(MouseEvent.CLICK, onClickStart);
    }

public function onClickStart(event:MouseEvent):void
{
    dispatchEvent(new NavigationEvent(NavigationEvent.START));
}

}

}

Arpee May 6, 2012 at 2:58 am

After this part I get this error
1120: Access of undefined property startButton.
The problem is in the MenuScreen.As and I made sure the button has an instance name. Any help please?

skippy85 May 7, 2012 at 4:51 pm

Ive added all the code for the restart button but i keep getting this error message, any ideas why?

C:\Users\IBM\Documents\programming\Classes\GameOverNotification.as, Line 14 1114: The public attribute can only be used inside a package.

skippy85 May 7, 2012 at 5:07 pm

I’ve found the problem.

Tinex May 18, 2012 at 4:18 am

Hi!

I am sure i follow you, i am following the tutorials too, but… how to remove the background from the menuscreen and gameoverscreen after pressing Start or Restart? Can you explain me? I can’t understand what TJ said. Thanks.

Lily June 25, 2012 at 10:00 am

I get to package
{
import flash.display.MovieClip;
import flash.display.SimpleButton;
import flash.events.MouseEvent;

public class GameOverScreen extends MovieClip 
{
    public function GameOverScreen() 
    {
        restartButton.addEventListener( MouseEvent.CLICK, onClickRestart );
    }

public function onClickRestart( mouseEvent:MouseEvent ):void 
{

}

}

}

point Using CS5 and keep getting 1061 error… Not sure if its an issue with Cs3 – Cs5 differences? Have been trying everything I could find and just adds up more issues. Any help would be greatly appreciated!

Lily June 25, 2012 at 10:05 am

Its the restartButton.addEventListener( MouseEvent.CLICK, onClickRestart ); line that doesnt seem to want to work

AM July 3, 2012 at 8:31 pm

Hi, I’m am trying to add 2 more buttons/screens (options/instructions) to the MenuScreen. I have made the buttons, but I don’t know what codes to use where to get the buttons to work (link to the corresponding screen). Can someone please help me?

Jonny B. July 15, 2012 at 8:54 am

I’m following your tutorial mostly to the letter (my game over screen however has two layers, one for a background and one for text). I create the button exactly as you say, then open up GameOverScreen for edit, and drag the button onto the page. I then name the instance as you say, and then create GameOverScreen.as. Then I run the program just as you say. I do not get the expected error message, and from that point nothing works like your tutorial. Any ideas what could be the trouble?

Jonny B. July 15, 2012 at 9:25 am

Note: if I continue on anyway with the tutorial, I start getting a compile error saying that restartButton is undefined. (btw I’m using CS5 if that makes any difference).

Sarunas July 30, 2012 at 8:03 pm

it is soo hard to read… maybe i’m too tired. I think it’s too complex

OSL September 4, 2012 at 1:48 pm

hi Michael..
I’m sure i am following your tutorial but i got this error

1180: Call to a possibly undefined method dispatchEvent.

at NavigationEvent.as
also i’m import the flash.events.MouseEvent in NavigationEvent.as
if i’m not, i got this error

1046: Type was not found or was not a compile-time constant: MouseEvent.

can you help me with the dispatchEvent problem? thx in advance

George November 19, 2012 at 11:42 pm

Bravo for all, but my question is about you for an UI to setup a map with how many tiles you need to create it. An example I have a 2 text box area each one represent how many rows and columns you need to create this map, just enter the numbers on the text boxes and get results is so super easy using AS2 but using AS3 is H.E.L.L!!!

So Master any light could you bring to my darkness WILL help a lot.

raco November 27, 2012 at 3:12 pm

hey

i have a problem with button. If i click, nothing happens… If try to do it other way by if statement, but i can’t figure it oust how to do it…

So back to your idea: we make restartGame(), but it’s not connected to GameOverScreen, This function does nothing? So i have tried to link it with onClickRestart, but again: nothing.

So i rly don’t know what to do anymore. Could someone pls check my file:
http://www.gamefront.com/files/22680359/Avoider+start4.rar

thx

Mark December 5, 2012 at 11:19 pm

Firstly excellent tutorials, possibly the best i have come across, so far however on
these tutorials setting these Screen objects to null is not cleaning them up for me.
im having to add removeChild(); to the correct function to remove them from window.

Am i doing something wrong?

public function DocumentClass() 
{
    menuScreen = new MenuScreen();
    menuScreen.addEventListener( NavigationEvent.START, onRequestStart );
    menuScreen.x = 0;
    menuScreen.y = 0;
    addChild( menuScreen );

}
public function onRequestStart(NE:NavigationEvent):void{
playScreen = new AvoiderGame();

        menuScreen=null;
        addChild(playScreen);
        playScreen.addEventListener(AvatarEvent.DEAD,onAvatarDeath);

// The game was not removing the menu screen and the game took place on top of the menu, i needed to add a removeChild(menuScreen); to clear up the menu screen.

    }

Emwat March 15, 2013 at 8:17 pm

I get this error after I click my restart button. Currently, my menu button’s not working, so the playScreen is temporarily the first thing that pops up until I can figure out what’s wrong with my buttons.

ArgumentError: Error #1063: Argument count mismatch on DocumentClass/onRequestRestart(). Expected 0, got 1.
    at flash.events::EventDispatcher/flash.events:EventDispatcher::dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at GameOverScreen/onClickRestart()

I checked the code on NavigationEvent.as and compared the code between GameOverScreen.as with MenuScreen.as to find not much.

Oh. And thank you for having these tutorials available! I’ve tried some book examples and didn’t get so far as I did with your tutorial.

Nagla March 18, 2013 at 1:12 pm

I am learning AS3 with this tutorial and it has been really helpful…but the question I have is that…from where does the function NavigationEvent knows weather to return the “restart” or “start” String??

Leave a Comment

Writing code? Write <pre> at the start and </pre> at the end to keep it looking neat.

Anti-Spam Protection by WP-SpamFree

{ 2 trackbacks }

Previous post:

Next post: