AS3 Avoider Game Tutorial, Part 3: Game Over

by Michael James Williams on October 9, 2008 · 223 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, I’ll show you how to add a game over screen. Click the image below to see how the game will play by the end of this post.

screenshot

Now, I already said in the first part of this tutorial that we’d be using just one frame of the timeline. This means that we can’t just stick a sign saying “game over” on frame 2 and then run a nextFrame() command when our character dies, so what can we do?

The answer’s pretty simple: we just slap a big “Game Over” sign on top of everything else when we need it, like pulling a curtain down at the end of a play.

Making an Overlay

Let’s get started. If you’ve been following the earlier parts of the tutorial, make a copy of your game folder and open the FLA in this new copy. Otherwise, download the zip file from Part 2, extract it somewhere, and open AvoiderGame-MJW.fla.

Create a new Movie Clip (Insert > New Symbol) called GameOverText, and draw something that will indicate to the player that their game is indeed over. Here’s mine:

screenshot

That font is Arial Black, and I’ve coloured it a dark red to make it stand out against the grey background. Note that I’ve centred the text around the registration point — see Part 1 for a reminder on how to do this.

If you’re using text, Flash might decide that it should be dynamic — that is, that it can be changed using code. Until we add scores, we don’t need this functionality, so click on your text and in the Properties panel, make sure to change the drop-down list from Dynamic Text or Input Text to Static Text. Otherwise, you’ll get an error:

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

Next we need to make this symbol available to our code. Find it in the Library, right-click it, and select Properties. In the Linkage panel, check the Export for ActionScript box, make a note of the class name (should be GameOverText) and click OK.

Open your document class file, either by directly opening the AS file in the Classes folder (mine’s called AvoiderGame.as), or by finding the document properties (click on an empty space, and selectWindow > Properties if you can’t see them) and clicking the little pencil icon next to the Document class text box. Find the onTick function, and then the piece of code that determines what happens if an enemy hits the player’s avatar:

?View Code ACTIONSCRIPT3
46
47
48
49
if ( avatar.hitTestObject( enemy ) ) 
{
	gameTimer.stop();
}

So at the minute, this just stops the whole game if the avatar collides with an enemy. Nothing wrong with that, but it looks like the game has just crashed. Let’s make our Game Over text appear as well:

?View Code ACTIONSCRIPT3
46
47
48
49
50
51
52
53
if ( avatar.hitTestObject( enemy ) ) 
{
	gameTimer.stop();
	var gameOverText:GameOverText = new GameOverText();
	gameOverText.x = 200;
	gameOverText.y = 150;
	addChild( gameOverText );
}

This code should be pretty familiar to you after reading Parts 1 and 2. Remember you can change the values 200 and 150 to alter where on the screen the Game Over text will appear.

Save everything and run it (Control > Test Movie) and when you hit an enemy, you should get something like this:

screenshot

Excellent.

Really Rubbing It In

An “overlay” game over notice like this is fine — it worked for Sonic — but what about a whole game over screen, like in Frozen Haddock’s game?

We can start by doing the same thing that we’re doing now, but making the symbol fill the whole game screen. Create another new Movie Clip, this time called GameOverScreen, and draw a big black rectangle, of any size. Click the rectangle, and change its size to match the dimensions of your stage. (You can change the size of the rectangle by altering its W and H — Width and Height — values in its Properties or Info panel, and you can see the dimensions of the stage by clicking Modify > Document.)

This time, we want the registration point of the symbol to be in the top-left corner. Why? Because then we can align it to the stage by setting its location to (0, 0), rather than having to worry about where the centre of the stage is. You can change the registration point by using the Align panel again:

screenshot

Alternatively, you can change the X and Y properties of the rectangle to 0.0, just as you changed the Width and Height.

Let’s add some text:

screenshot

That’ll do. You can pretty it up if you like. When you’re ready, Export GameOverScreen for ActionScript, just as we did with GameOverText.

Open the document class again, and find the code we modified before:

?View Code ACTIONSCRIPT3
46
47
48
49
50
51
52
53
if ( avatar.hitTestObject( enemy ) ) 
{
	gameTimer.stop();
	var gameOverText:GameOverText = new GameOverText();
	gameOverText.x = 200;
	gameOverText.y = 150;
	addChild( gameOverText );
}

It’s pretty simple to make this work with our new screen. Have a go yourself if you like. My code’s here:

?View Code ACTIONSCRIPT3
46
47
48
49
50
51
52
53
if ( avatar.hitTestObject( enemy ) ) 
{
	gameTimer.stop();
	var gameOverScreen:GameOverScreen = new GameOverScreen();
	gameOverScreen.x = 0;
	gameOverScreen.y = 0;
	addChild( gameOverScreen );
}

Note that I changed the x and y coordinates to zero. If you save and run the game and hit an enemy, you’ll see something like the following:

screenshot

But we can go further with this. We can put the actual game inside its own symbol. This way, rather than dropping a curtain down in front of the stage and leaving all the actors standing around behind it, we can have all the actors in their own glass box, and remove this box from the stage when we drop the game over curtain. This makes the stage much less cluttered, and the actors easier to manage. The only question is, have I gone too far with this analogy?

Adding a Game Screen

Let me clarify this a little. At the minute, our game is set out like this:

screenshot

The document class is controlling pretty much everything. If we continue making it do so, then if we want to add a title screen, a menu screen, a few more levels, a character selection screen, and so on, then the document class is going to get very very bloated.

Let’s separate things a little bit. Here’s what I’m proposing:

screenshot

Much neater! The document class duties only consist of making sure the player is seeing the right screen. Each individual screen manages its relevant parts. Later we might break this down even further, but this is absolutely fine for now.

How do we implement this? Well, you probably won’t be surprised if I tell you that we need to make a new Movie Clip — this time, call it PlayScreen.

This new screen is going to do roughly the same thing as our entire game was doing by the end of the last part. That is, it’s going to contain the avatar, and it’s going to generate the enemies and make them move within it. One important difference between using a Movie Clip to contain everything versus using a document (as we were doing before) is that a document has a default background already set up (ours is grey), but a Movie Clip doesn’t — we have to add one ourselves.

Let’s do that now! Edit your PlayScreen Movie Clip and draw a filled rectangle. Just as with GameOverScreen, make this rectangle the same size as the stage, and set its registration point to the top-left corner. I’ve made mine a very light blue, so as to stand out against the editor’s background:

screenshot

We’re not restricted to using a plain background this time. Because I’m so vain, I’ll demonstrate this by sticking my initials all over the place:

screenshot

Alright great. Obviously you don’t have to use my initials. Or any initials at all, for that matter. You could draw a cave, or a black hole, or a chat window (since the game is about smilies! get it?) or whatever.

Now for the code. I already said that this screen is going to do the same thing as our game already was doing, so you can imagine that it’ll require almost exactly the same code. We could rewrite all this code from scratch. We could copy and paste it, renaming bits as required. Or… we could take advantage of our marvellous object-oriented design.

Remember that the entire game, the entire document, is basically a Movie Clip. When we assign it a document class, this is essentially the same as selecting a Movie Clip from the library and assigning it a Class when we “Export it for ActionScript”. So, there’s no reason that we couldn’t assign PlayScreen the same class that has, up till now, been the document class.

Right-click PlayScreen in the library, select Properties, and check Export for ActionScript. This time, instead of accepting the default value, enter the name of your document class. Click OK.

screenshot

Oh, right. First we’ll have to make a new document class, since no two different objects can share the same class. Cancel the Properties box.

A New Class of Document

Hit File > New and select ActionScript File. Enter the (by now familiar) code:

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

Save this in the Classes directory as DocumentClass.as. (There’ll be no confusing the purpose of this file!) Now, back in your FLA, change the document class to DocumentClass.

screenshot

Check everything’s fine by clicking that pencil icon — if it’s all OK, that should bring up the AS file that you just created.

Now you can set the PlayScreen‘s class to AvoiderGame. So do so!

If you save and run the game now, nothing will happen — that’s because the document class isn’t pulling in the PlayScreen. Head back to the DocumentClass AS file and modify it like so (lines 5, 7, and 8):

?View Code ACTIONSCRIPT3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package 
{
	import flash.display.MovieClip;
	public class DocumentClass extends MovieClip 
	{
		public var playScreen:AvoiderGame;
 
		public function DocumentClass() 
		{
			playScreen = new AvoiderGame();
			addChild( playScreen );
		}
	}
}

This is pretty much exactly the same code as the AvoiderGame AS file uses to create a new Avatar, though here we’re using it to create a whole game. Save it and run:

screenshot

Awesome.

AvoiderGame Once Removed

Actually we’re not quite done yet. Here’s the sketch of my proposed new setup:

screenshot

And here’s our current setup:

screenshot

We’ve got the same problem as before — a bloated class file — only now it’s not the document class. We want the document class to be pulling in the Game Over screen when the player dies. How can we do this?

If we were using AS2, we might use _root or _stage to tell the document to do something. We’re not going to do that.

In previous versions of this tutorial, I let the playScreen run a function in the document class directly. That’s probably the simplest way of handling things, but it gets very messy very quickly. Even with a game as simple as this, I got a few emails letting me know of problems this quick fix had caused. So we’re not going to do that, either.

Back in Part 1, when we were adding the game timer, I said:

An event listener is like a robot that’s constantly checking to see if a particular “event” has occurred, and which runs another function if so.

The line we used for this was:

?View Code ACTIONSCRIPT3
gameTimer.addEventListener( TimerEvent.TIMER, onTick );

(If you’ll recall, that line ran a function called onTick whenever the Timer “ticked”.)

What I’d like to do now is place a similar event listener on playScreen (line 11):

?View Code ACTIONSCRIPT3
8
9
10
11
12
13
public function DocumentClass() 
{
	playScreen = new AvoiderGame();
	playScreen.addEventListener( AvatarEvent.DEAD, onAvatarDeath );
	addChild( playScreen );
}

AvatarEvent.DEAD isn’t a built-in Flash event, of course, but we’ll get to that later. Right now let’s write the onAvatarDeath function into the document class:

?View Code ACTIONSCRIPT3
15
16
17
18
public function onAvatarDeath( avatarEvent:AvatarEvent ):void
{
 
}

This is just like the onTick function from AvoiderGame.as. Just as then, we need to give it some code to run:

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

Lines 17-20 are copied straight from AvoiderGame.as. Line 22 introduces a new keyword: null. By setting an object equal to null you are essentially resetting it. All event listeners are removed, all contained objects are erased, all functions cease to exist. After being set to null, playScreen is in exactly the same state as before the line playScreen = new PlayScreen(); — this means that the next time we want to use it, we need to run that line again. Nullifying the playScreen will also remove it from view.

Now we need to actually trigger this event.

A Grand Event

You know how our Avatar, Enemy and AvoiderGame classes extend MovieClip so that they can do everything a MovieClip can do? Well, TimerEvent extends a class called Event in the same way. This means that we can make our own kind of event (the AvatarEvent I’ve been talking about) by extending Event, too.

So, let’s try that out, in the same way that we extended MovieClip all those times. Start a new AS file, AvatarEvent.as:

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

This looks about right, but actually, there’s a problem. When you create an Event of any kind, it expects you to pass through the type of event in the same way that our Enemy class expects you to pass through an x- and y-coordinate — for example, an Event to tell an object to scroll is created like this:

new Event( Event.SCROLL )

We’ve not provided a way to specify the type of event like that in our code, so let’s add that in:

?View Code ACTIONSCRIPT3
1
2
3
4
5
6
7
8
9
10
11
package  
{
	import flash.events.Event;
	public class AvatarEvent extends Event 
	{
		public function AvatarEvent( type:String )
		{
 
		}
	}
}

Now we need to add a type of event for us to use. We can use a public const for this; it’s like a public var except it can’t be changed after you’ve hit Test Movie:

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

Great, now we’ll be able to write:

new AvatarEvent( AvatarEvent.DEAD )

…because static consts belong to the class AvatarEvent, not to any specific instance of AvatarEvent.

It’s nearly ready to use, but we need to figure out what to do with this type that gets passed in to the new AvatarEvent. Well, actually… we don’t! Events already know what to do with a type that’s passed in to them, so we just need to “borrow” their code.

We can do this using the super() function, like so:

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

What super( type ) does is, it runs the code from inside the constructor function of the Event class, and passes type through to that. That means we let the existing code (which we can’t see) inside the Event class deal with everything. Fine by me :)

(We’ll look at super in more detail in Part 5. In the meantime, feel free to check out my post about extends, override, and super.)

Now that we have the event listener and the event class, all that remains is to fire off the event when the avatar dies (i.e., when it hits an enemy). Head back to AvoiderGame.as and change this:

?View Code ACTIONSCRIPT3
46
47
48
49
50
51
52
53
if ( avatar.hitTestObject( enemy ) ) 
{
	gameTimer.stop();
	var gameOverScreen:GameOverScreen = new GameOverScreen();
	gameOverScreen.x = 0;
	gameOverScreen.y = 0;
	addChild( gameOverScreen );
}

to this:

?View Code ACTIONSCRIPT3
46
47
48
49
50
if ( avatar.hitTestObject( enemy ) ) 
{
	gameTimer.stop();
	dispatchEvent( new AvatarEvent( AvatarEvent.DEAD ) );
}

Line 49 fires off an AvatarEvent of type DEAD. That’s all there is to it. I removed all the code about the Game Over screen because we’re dealing with that in the document class now.

Save it and run, and hey, what do you know, it all works as it should.

I realise that this last big change didn’t change the game in a way that the player could notice, but reorganising the internal structure like this will certainly make it a lot easier to add new features in the future. I’ll prove this in the next part, where we’ll add a title screen and a reset button with minimal effort — available here.

Also, if you like, you can grab the zip with all the files I’ve been using so far from here.

{ 220 comments… read them below or add one }

Michael Williams May 16, 2010 at 1:55 pm

@Tom: Like ayumilove says, check out the debugging guide and figure out where exactly in your code it’s going wrong. Write down what you expect the code to be going, then use trace() statements to see what’s different.

@Crump: Don’t feel stupid! This is pretty complicated. You’ve got super() right, more or less: it lets you use the functions of the class that you are extend-ing.

Actually, PlayScreen doesn’t call AvatarEvent, it creates an AvatarEvent. You can then add an event listener to playScreen from within the document class to detect when this AvatarEvent is created, and run code based on that. It’s exactly the same as when you add an event listener to a button to see when the user clicks it :)

So, within DocumentClass, you do something like:

playScreen.addEventListener( AvatarEvent.DEATH, onAvatarDeath );

…then, when PlayScreen creates a new DEATH AvatarEvent, the document class will detect this and run the onAvatarDeath() function.

Make sense?

ayumilove May 16, 2010 at 1:57 pm

@Crump

It’s kinda straight forward.

The DocumentClass has established an addEventListener on AvoiderGame
In simpler terms, the documentClass is listening to avoiderGame event.
Any events that are dispatched by AvoiderGame instance, it will do something.
But to do something, it must first match with the event id called AvatarEvent.DEAD

As you can see in AvoiderGame.as class,
it dispatches an event called AvatarEvent.DEAD when
the avatar (your hero in the game) collides any enemy.

In short,
The avoidergame.as loops through an array of enemies,
checking whether any enemy hits the avatar (your hero)
If it collides, create a new custom event called AvatarEvent,
and attach an event id (string datatype) called AvatarEvent.DEAD
AvatarEvent.DEAD represents the string “dead”.
Once it completed constructing that custom event, it dispatches the event.

The avoidergame.as shouts out to everyone, I am dispatching an event
called AvatarEvent.DEAD.

Now on the other side of our class (in the DocumentClass)
The documentClass is interested in a particular event tagged with
AvatarEvent.DEAD.

If AvoiderGame.as dispatches this event, the documentClass
will trigger the onAvatarDeath function to create a new instance
of gameOver on top of the PlayScreen, and set playScreen as null.

Joey May 16, 2010 at 2:58 pm

I was thinking that the way you made the GameOver Screen was a little shabby.

I did mine like this:

if (avatar.hitTestObject(enemy)) {
                enemy.gotoAndPlay(5);
                gameTimer.stop();
                //BLACKSQUARE
                var black:Sprite = new Sprite();
                black.graphics.beginFill(0x000000);
                black.graphics.drawRect(0,0,450,450);
                black.graphics.endFill();
                stage.addChild(black);
                //Added Black Square
                var gameOverText:GameOverText = new GameOverText();
                gameOverText.x = 225;
                gameOverText.y = 225;
                black.addChild(gameOverText);

Is that more efficient or not?

Thanks :)

Michael Williams May 16, 2010 at 3:03 pm

You mean, rather than creating a whole new symbol, creating the black background in code and adding the text to that black background?

Yeah, yours is much more efficient in that case :) Nice.

Joey May 16, 2010 at 3:07 pm

Thanks. I have one little problem though.
How do I make a delay for the game over screen to appear?
I have a dying animation for the enemies and I want that to play first. If I found out how to make a delay for things, this would help me in future games (turn based strategies and things). Would really appreciate the help :)

Michael Williams May 16, 2010 at 3:18 pm

There are a few ways of doing this.

You could create a new Timer, and set it to only run once (the first argument is number of milliseconds between events, second is number of times to run, so new Timer( 1000, 1 ) will create a Timer that waits one second, fires off a TIMER event, then stops).

You could use flash.utils.setTimeout().

You could repeatedly check which frame the enemies were currently playing, and, if they’d reached the last frame, create your game over screen.

You could add code to the timeline of the Enemy animation inside the Flash IDE, in the last frame, putting dispatchEvent( new Event( Event.COMPLETE ) ), and then add an event listener to your enemies, listening for this event…

Lots of options :) Try them out, see what works best for you.

Crump May 16, 2010 at 3:24 pm

Thanks a bunch MJW and ayumilove, I completely forgot about the EventListener, makes all the sense in the world now :D

And meh, me writing call is because I usually program in python, damn terminology changing!

Thanks again, awesome tutorial!

Joey May 16, 2010 at 3:43 pm

So lets say I set the new timer

new Timer( 1000, 1 )

,
How would I put it in the HitTest, so that it runs after the player hits the enemy. Also, how do I make the gameover screen appear at the end of the timer?

Can you give me a code snippet?

Michael Williams May 16, 2010 at 3:55 pm

@Crump: Great! Cheers.

@Joey: something like:

if (avatar.hitTestObject(enemy)) {
    var gameOverDelayTimer:Timer = new Timer( 1000, 1 );
    gameOverDelayTimer.addEventListener( TimerEvent.TIMER, onGameOverDelayTimerTick );
    //...other code
}

Then the onGameOverDelayTimerTick() function will run after a second :)

How’s that?

Joey May 16, 2010 at 4:08 pm

Worked a charm, thanks!

Problem Child June 6, 2010 at 7:09 am

Hey there!
Pretty AWESOME tutorials! have taught me a lot – thank you!

I am having a problem with the null arguement, i have it placed just as you do, using CS5…and I cannot for the life of me get the screen to disappear. I mean, if it swaps to the playScreen, the menuScreen is visable behind the play screen, and if i die, it’ll go to game over, but leave the playScreen a bit visable, if I swtich back to menu from the game over screen, i can actually still click, restart/menu or start…all buttons are “visable”….

Do you know what I may have done wrong?

thank you in advance bro!

Problem Child June 6, 2010 at 7:10 am

Sorry for this repost, but I missed the check box “notify by email when response”
-thank you again
Hey there!
Pretty AWESOME tutorials! have taught me a lot – thank you!

I am having a problem with the null arguement, i have it placed just as you do, using CS5…and I cannot for the life of me get the screen to disappear. I mean, if it swaps to the playScreen, the menuScreen is visable behind the play screen, and if i die, it’ll go to game over, but leave the playScreen a bit visable, if I swtich back to menu from the game over screen, i can actually still click, restart/menu or start…all buttons are “visable”….

Do you know what I may have done wrong?

thank you in advance bro!

James June 11, 2010 at 9:22 pm

@Problem Child
Are you sure you’ve done removeChild()? Someone correct me if I’m wrong but as far as I’m aware theres no difference been made to AS3 for CS5 so it shouldnt matter about that.

Michael Williams June 12, 2010 at 2:14 pm

@Joey: Good to hear :)

@Problem Child: Thanks!

As James says (thanks James) there’s no huge difference to AS3 in CS5. A few new features have been added, but nothing major has been edited or removed.

It does sound like you’re not calling removeChild() on the screens. Are you? Are you receiving any errors when you do?

Josh June 12, 2010 at 10:05 pm

I’m lost at the point where you have to make DocumentClass the document.
I go to Modify>Document… and there’s no text box anywhere in there.

I’m using CS5, and probably doing it wrong. I’m very new to AS3 and flash, and am using this tutorial to get my bearings with it.

Any help would be great.

Josh June 13, 2010 at 4:35 am

I figured it out. I’mma stupid.

I have another question though…
I was looking around for physics tutorials to play around with it, and I noticed that people seem to just make the game in the first frame without organizing it like you did.
I like the way you did it better, it seems more logical and organized, is doing it in the first frame wrong?
I want to know if I should bother trying to figure out how to make it with all the classes etc when the tutorial is using it all in one frame.

Michael Williams June 22, 2010 at 3:38 pm

Hey Josh,

Glad you fixed it :)

I think a lot of tutorials do it in one frame because it’s easier to get to the real meat of the tutorial that way; you don’t have to spend all that time explaining how to set up the classes and so on. You could follow the tutorial with all the code in one frame, and then (once you understand it) write your own version with classes.

ayumilove June 22, 2010 at 3:57 pm

@Josh
The best is “Don’t code a thing in 1st frame”
All in classes :)

Geoffrey Wong July 11, 2010 at 12:49 pm

I just spent 2 hours figuring this out, and I think I know what the issue Jamie Steel had. (He posted an error similar to mine on August 4, 2009 at 5:52 pm).
He and I was receiving

Error 1119: Access of possibly undefined property DEAD through a reference with static type Class.

With using

public static const DEAD:String = "dead";

in the “AvatarEvent” class.

I simply changed everything to died and it worked just fine. I believe “DEAD” might be a reserved word somewhere, which would make sense if him simply re-doing (thus possibly leaving out a class that is already using DEAD).

Furthermore, I have in my same AvatarEvent file the line:

public static const HIT:String = "hit";

and i had no issue using “HIT”, but still having issue with “DEAD”.

=============================

And also, excellent guide.

Michael Williams July 23, 2010 at 11:53 am

Hey Geoffrey,

That’s weird! I don’t know why “DEAD” wouldn’t be working — or at least, why it would be giving you that error, when “HIT” and “DIED” doesn’t. Makes no sense to me, but hey, at least you fixed it :) Good job, and cheers for sharing!

Also, thanks for your kind words.

Brice August 21, 2010 at 6:13 pm

Hey !
First of all, thank you for this amazing, clear and complete tutorial. It help me a lot.

As “Problem Child”, I just like to understand the part where you say that “Nullifying the playScreen will also remove it from view”, but it don’t on my computer.
Ok, I can do it with a simple “removeChild”, but i like to understand why the playScreen stay on the view (behind the gameOverScreen) ?

Thank you again for this ! :)

Michael Williams August 21, 2010 at 6:20 pm

Hey Brice, thanks for your kind words!

That’ll be explained in Part 12, so you’ll understand it then — I hope :)

Elena September 10, 2010 at 9:08 am

Hi,

I’m not sure if anyone asked this before, but what’s the point in creating GameOverText, when right after we create GameOverScreen and abandon the text? :/

Michael Williams October 5, 2010 at 12:59 am

Hey Elena,

It’s basically to show a quick method you can use, before moving into the more complex ideas of having different screens.

Jim November 15, 2010 at 3:03 am

I think there’s something not quite right about the null statement. Setting something to null doesn’t remove it from the display list. In fact if you repeatedly retry, the game and game over screens pile up. You would need to use removeChild(). You can tell by using a trace(numChildren) command in the document class.

Cesar December 18, 2010 at 10:52 pm

Hi
I’m having a trouble when I link the flash document with the DocumentClass and the PlayScreen movie clip with AvoiderGame class. the Document class doesn´t recognize AvoiderGame class and shows me this error: 1046: Type was not found or was not a compile-time constant: AvoiderGame. i don´t understand why. But if i make an instance of a the other classes it works just fine.
I really need some help i’ve tried everything i even repeat al the linking and code

yogi iswantelly suryadinata January 7, 2011 at 3:11 pm

why when I follow ur guide i got
1046: Type was not found or was not a compile-time constant: avatarEvent.
actually i already import the flash.events.Event; also got the same error.
i wonder why. could u help me?

Johan January 12, 2011 at 9:24 pm

Got this error. I used Char instead of Avatar, but i can’t figure out whats wrong :S

ArgumentError: Error #1063: Argument count mismatch on DocumentClass/onCharDeath(). Expected 0, got 1.
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at AvoiderGame/onTick()
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()

Mark March 8, 2011 at 8:09 pm

I’ve been going through avoiderGame again. I’ve removed the ‘AvatarEvent.as’ file and simply added the ‘public static const DEAD:String = “dead”‘ line to the NavigationEvent.as file. Everything works ok – but is there any reason why i shouldn’t do this? Is there a reason you had NavigationEvent.as and AvatarEvent.as files instead of just one file?

numbus March 16, 2011 at 4:16 am

I did everything the way you did and I got 4 errors. I fixed all 4 and got a totally new error: “Access of undefined property onAvatarDeath.” For DocumentClass.as Line 11. Any help?

Alex May 9, 2011 at 2:24 pm

[Quote] I’m lost at the point where you have to make DocumentClass the document.
I go to Modify>Document… and there’s no text box anywhere in there.

I’m using CS4, and probably doing it wrong. I’m very new to AS3 and flash, and am using this tutorial to get my bearings with it. [/Quote]

The text above me pretty much explains what I’m having problems with (edited a bit), but no solution to it.
Very nice tutorial overall this far, except from the feeling its getting “sloppier” the longer it goes.
Feels like you jump parts that I would love to have explained, again.. After all, I’m very new at this.

Eva May 24, 2011 at 10:53 am

Hey guys!
I have a problem, when the game starts, the menuScreen becomes the background image, and when i push the restart button and the game restarts the gameOverScreen stays in the background!

What to do to change this?

Tim May 29, 2011 at 5:38 am

lol read this:

“Create another new Movie Clip, this time called GameOverScreen, and draw a big black rectangle, of any size”
If you told us it has to be big, why did you say right after that it could be any size?
jk I understand what you mean, but it still is funny.

Michael James Williams May 30, 2011 at 11:42 pm

@Tim: Haha, good point :)

Angela June 30, 2011 at 8:05 pm

Hi MJW,
I’m adding a start menu (like in the next in the series), but “null” isn’t doing what I’d like it to do – or what your tutorial suggests it should be doing.
To quote your tutorial:
“By setting an object equal to null you are essentially resetting it. All event listeners are removed, all contained objects are erased, all functions cease to exist….Nullifying the playScreen will also remove it from view.”

I have no image as a background for my game, so when I hit the start button, the menuScreen is in the background of my game. To fix the problem, I added “removeChild(menuScreen)”. Can you explain why I shouldn’t do that and why the null didn’t remove the menuScreen from view?

package 
{

import flash.display.MovieClip;

public class DocumentClass extends MovieClip
{
public var menuScreen:MenuScreen;
public var playScreen:Game;

public function DocumentClass()
{
    menuScreen = new MenuScreen();
    menuScreen.addEventListener( NavigationEvent.START, onRequestStart );
    menuScreen.x = 0;
    menuScreen.y = 0;
    addChild( menuScreen );
}
public function onRequestStart( navigationEvent:NavigationEvent ):void
{
    playScreen = new Game();
    removeChild(menuScreen);
    addChild( playScreen );
    menuScreen = null;
}

}

}

Joe Man July 4, 2011 at 12:31 am

Hey, when my avatar hits an enemy as soon as the enemy spawns the Game Over screen shows. But if i wait until the enemy is at the bottom of the screen and i try to hit it then the game over screen dosent show, it just freezes. Why is this? Thanks!

Melon Bomb July 13, 2011 at 11:53 pm

Hey, thanks for the tutorials and the suggestions for extensions.
I’m stuck at the end of this tutorial I’ve tried everything but putting DocumentClass’ class “Avoider Game”, when I test this game, it doesn’t get pulled in and not even the background. Please help, Thanks.

Melon Bomb July 14, 2011 at 8:08 pm

Sorry for the double post what I mean is, am I supposed to change DocumentClass’ class to “AvoiderGame” or is there something I’m missing.

Melon Bomb July 15, 2011 at 4:42 am

Nevermind, I fixed it.

TimeThereWere July 24, 2011 at 10:26 pm

setting my game screen object to null is doing nothing. I know the custom event listener is function because the function that it triggers only has two lines of code – one to bring up the game over screen and the other to set the game screen to null.

The game over screen pops up and covers up all of my game objects so I can’t SEE them – but I know they’re still there because the sounds I set up are still playing, and if I comment out the line that adds the game over screen then nothing happens when flash hits my “screen = null” line.

I didn’t follow this tutorial exactly… its more like I used it to figure out how to do a few things in my game that I didn’t know how to do on my own. I suppose that means I probably set up my game in such a way that setting the game class object to null doesn’t actually do anything.

The compiler isn’t throwing any errors.

Any idea what one might do to cause this to happen? I made sure none of my movieclips were set to start in frame 1.

Fireball916 July 29, 2011 at 1:26 am

When I did the GameOverScreen everything worked out but when I did the steps to make it more organized, when I test it and when I die the GameOverScreen is up in the corner and you cant see it. I can’t seem to figure out why it does that.
Thanks
(I’m sorry if I didn’t explain the problem well. :/)

Johnny August 19, 2011 at 8:34 am

Thank you for this amazing tutorial,
I haven’t coded a single line in my life and have always been afraid of starting. But you changed my perception of coding.
However, I’m stuck setting the PlayScreen‘s class to AvoiderGame, although my code in DocumentClass.as and AvoiderGame.as is the same as yours.
I still get the error message from above: “”Please enter a unique class name …”

Btw, I’m Using CS 5.5
Cheers!

Jon August 25, 2011 at 2:52 pm

Hey fella, great tutorial so far.

I’m getting an error “DocumentClass.as, Line 11 1120: Access of undefined property onAvatarDeath” and can’t figure out where i have gone wrong?

package 
{
    import flash.display.MovieClip;
    public class DocumentClass extends MovieClip 
    {
        public var playScreen:AvoiderGame;

    public function DocumentClass() 
    {
        playScreen = new AvoiderGame();
        playScreen.addEventListener(AvatarEvent.DEAD, onAvaterDeath);
        addChild(playScreen);
    }

public function onAvatarDeath(avatarEvent:AvatarEvent):void
{
    var gameOver:GameOver = new GameOver();
    gameOver.x = 0;
    gameOver.y = 0;
    addChild(gameOver);

    playScreen = null;
}

}

}

Cheers

Jon August 25, 2011 at 3:01 pm

playScreen.addEventListener(AvatarEvent.DEAD, onAvaterDeath);

Would help if I could learn to spell Avatar correctly *the shame

rock September 9, 2011 at 4:05 pm

PLEASE HELP I GOT THIS ERROR :-(

 TypeError: Error #1009: Cannot access a property or method of a null object reference. 

Jonathan October 19, 2011 at 8:17 pm

I have completed this part of the tutorial, but the last change you make gives me an error that says:


C:\Documents and Settings\Administrator\My Documents\Flash Games\AvoiderGame\Classes\DocumentClass.as, Line 1 5006: An ActionScript file can not have more than one externally visible definition: DocumentClass, onAvatarDeath

What did I do wrong?

Jonathan October 19, 2011 at 8:24 pm

Oh yeah, please tell me if I need to tell you any codes that I’ve done, or anything in-game that I have done also.

Tim October 25, 2011 at 8:30 pm

I get the exactly same error as Jonathan:

C:\Documents and Settings\**********\ My documents\AvoiderGame\Classes\DocumentClass.as, Line 1 5006: An ActionScript file can not have more than one externally visible definition: DocumentClass, onAvatarDeath

What is the solution for this?? Please help!!!

davidp October 27, 2011 at 1:44 pm

guys check you parenthesis – {}. It seems to me you have a function that’s OUTSIDE the class.

public class document
{
    pubilc some_function()
    {}
}

will work just fine while

public class document
{

}
pubilc some_function()
{}

throws out the error you described.

cheers!

davidp October 27, 2011 at 1:45 pm

public class document
{

}
public some_function()
{}

fix*

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

{ 3 trackbacks }

Previous post:

Next post: