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 }

asdf September 10, 2009 at 8:39 pm

Here’s one
http://www.kongregate.com/games/Buhummith/4-side

But like I said, I made it a while ago.

Michael Williams September 11, 2009 at 1:11 pm

Neat concept. It hurts my brain though :P

asdf September 11, 2009 at 8:46 pm

That was my second game, then I started to work on another but I abandoned it because my code was too sloppy and unorganized. It would’ve been pretty good though.

Dee September 15, 2009 at 11:23 pm

When I hit one of the enemies I get an error.

TypeError: Error #1034: Type Coercion failed: cannot convert “dead” to AvatarEvent.
at AvoiderGame/onTick()
at flash.utils::Timer/flash.utils:Timer::_timerDispatch()
at flash.utils::Timer/flash.utils:Timer::tick()

I have gone through and check my code against the tutorial and cant find any mess ups.

Michael Williams September 16, 2009 at 2:10 pm

@asdf: Cool, let us know when you finish your next one :)

@Dee: At a guess, I’d say that instead of this line:

dispatchEvent( new AvatarEvent( AvatarEvent.DEAD ) );

…you’ve got this:

dispatchEvent( AvatarEvent.DEAD );

See the difference? I’ve made that mistake a bunch of times ;)

Dee September 16, 2009 at 6:58 pm

Thank you. I missed the “new”. I can usually find the typos myself but this time i didnt even begin to understand the error message.

Michael Williams September 17, 2009 at 5:48 pm

Yeah, that’s a confusing one. It’s caused because AvatarEvent.DEAD is a public static const with the value of "dead". So when you type:

dispatchEvent( AvatarEvent.DEAD );

…you’re basically typing:

dispatchEvent( "dead" );

…and since “dead” is a String instead of an AvatarEvent, you get the message telling you that Flash can’t convert “dead” to an AvatarEvent.

FlashN00B September 20, 2009 at 10:29 am

I get how I build an event, but not how I can make this event return some variables…

Like with the Keyboard statement. It returns the keycode.
Now I want an event that returns the position on which the avatar died.

How can I do that?

Michael Williams September 22, 2009 at 12:22 pm

Hey FlashN00B, good question.

What you need to do is add a new variable to the AvatarEvent AS file, like this:

package
{ import flash.events.Event; public class AvatarEvent extends Event { public static const DEAD:String = "dead"; public var avatarX:Number; //new! public var avatarY:Number; //new!

Next, you need to allow values for these variables to be passed in to the event:

        public function AvatarEvent( type:String, avatarsXPosition:Number, avatarsYPosition:Number, bubbles:Boolean = false, cancelable:Boolean = false ) 

See how I’ve added two new parameters to the constructor? This means you have to find the places where you’ve written newAvatarEvent() and insert the values, like so:

dispatchEvent( new AvatarEvent( AvatarEvent.DEAD, avatar.x, avatar.y ) );

Next we need to set the new variables inside the AvatarEvent to be equal to the parameters passed in:


    public function AvatarEvent( type:String, avatarsXPosition:Number, avatarsYPosition:Number, bubbles:Boolean = false, cancelable:Boolean = false ) 
    { 
        super( type, bubbles, cancelable );
        avatarX = avatarsXPosition;
        avatarY = avatarsYPosition;
    } 

Now you’ll be able to access avatarEvent.avatarX and avatarEvent.avatarY to find out where the avatar was at time of death.

There’s one more change we need to make, though: the clone() function. This is used automatically by Flash to make a copy of the existing event. Remember I said we needed to change all the code where we’d called new AvatarEvent()? Well, same applies here. It’s a simple change:

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

And that should do it :)

I’ve rushed through this a bit, so please let me know if you’d like any more details.

FlashN00b September 22, 2009 at 3:53 pm

Nope. I get now how I can do things like this.

Thanks :)

Michael Williams September 22, 2009 at 4:48 pm

Great! :)

Michael Williams September 27, 2009 at 11:26 pm

Hi everyone,

I made some changes to the tutorial, greatly simplifying the “A Grand Event” section. I’m hoping this makes custom events a lot easier to understand. Let me know if I made any mistakes ;)

Patu October 14, 2009 at 3:45 pm

I made like i should do and i get error:
5008: The name of definition ‘AvatarEvent’ does not reflect the location of this file. Please change the definition’s name inside this file, or rename the file. I:\Files\Flash CS4\Avoider\Classes\Avatar.as
My code is:

 package
{ import flash.events.Event; public class AvatarEvent extends Event { public static const DEAD:String = "dead";

    public function AvatarEvent( type:String )
    {
        super( type );
    }
}

}

Nathan October 15, 2009 at 5:23 am

do I create a new .as for the avatar package

Michael Williams October 15, 2009 at 5:26 pm

@Nathan: Yep, that’s right. Although… that was back in Part 1; you don’t need to make a new Avatar.as file in this part.

Michael Williams October 15, 2009 at 9:30 pm

@Patu: Ah, you need to create a new AS file called AvatarEvent.as and put that code in there. You don’t need to change the contents of Avatar.as.

Patu October 16, 2009 at 8:22 am

Thanks! I got it. Great tutorial

Michael Williams October 16, 2009 at 6:40 pm

@Patu: Good good :)

davidp November 7, 2009 at 12:24 am

I’m having a problem with my game at creating new game screen.

it seems i get 1009 error on this line:

playgame = new Main();

when my code looks like this:

    public class DocumentClass extends MovieClip 
    {
        public var playgame:Main;

    public function DocumentClass() 
    {
        playgame = new Main();
        //addChild(playgame);
    }
}</pre>

(Main being my Main.as class, set for movie clip PlayScreen- a main .as for the game). What bugs me, is clicking on PlayScreen and seeing no base class set for PlayScreen. But it's not set for bullets, enemies or player either and everything works well. Mega strange.

Michael Williams November 7, 2009 at 11:45 am

Hey davidp,

That code looks fine to me, so I guess the problem must be somewhere else. Does your PlayScreen movie clip (in the library) have a class name of Main? When you click the pencil next to the class name (in the place where you can edit it) does it open your Main.as file?

davidp November 7, 2009 at 11:57 am

yes, clicking PlayScreen’s pencil for class opens Main.as. Also, If i normally run game with scrambleFlash.fla and Main.as associated as class everything runs fine. then i add PlayScreen, associate DocumentClass.as with scrambleFlash.fla and Main.as with PlayScreen as you have in your tut, and then…well run it, getting the error. Also, this might help:

TypeError: Error #1009: Cannot access a property or method of a null object reference.
    at Main()
    at DocumentClass()

So, this could mean something is wrong with Main? But it runs okay, when ran from scrambleFlash.as, so it shouldn’t be, or am i wrong? I’ve been also checking your part4.zip and everything seems the same as mine, only changed names. So i don’t know what am i missing. Hm. Well, don’t bother with it, just saying. I guess i’ll just work on gameplay stuff and return to menus later.

Michael Williams November 7, 2009 at 12:19 pm

Oh! Well, from that error message it looks like there might be a problem somewhere inside Main’s constructor function, and it just looks like the problem is inside DocumentClass because Main itself is being run by DocumentClass.

See if you can narrow down that #1009 error to a single line; it’ll almost certainly be in the Main() constructor function. Check out the first part of my guide to debugging to see how to narrow things down.

davidp November 7, 2009 at 1:07 pm

Yes, I’ve been trying to test things, but trace has proven to be useless (as game don’t run at all atm), so i’ll go and comment stuff one by one. I’ll get back to you when I find the problem :) thanks.

Oh and great tutorial by the way. God job.

Michael Williams November 7, 2009 at 1:26 pm

Aha OK. Well let me know when you find something. And thanks :)

davidp November 9, 2009 at 6:19 pm

I’ve been working with game all over the weekend, banging my head against the wall but nothing helps. would you be willing to check my code? it’s only few lines long with two symbols (player char and level) and two .as files (document class and main)?

here is the source:
http://www.box.net/shared/pmzccf51in
(zipped under Document Class, but all 4 files are in there)

I wouldn’t bother you, but I’m really desperate.

i really don’t know what am i doing wrong :/

Michael Williams November 10, 2009 at 11:16 am

Hey Davidp,

Sorry, I can’t open the FLA because it’s in CS4 format. If you’d like to “Save As” in CS3 format I’ll take another look, though.

davidp November 10, 2009 at 12:13 pm

I’ve uploaded version with CS3 – it’s ss_flash3.fla. download link is the same. thank you a lot!

Michael Williams November 10, 2009 at 1:18 pm

Cheers — found it!

You’ve got a reference to “stage” in your constructor function of Main(), but “stage” actually doesn’t refer to anything until Main has been addChild-ed to the DocumentClass.

This is pretty confusing, but don’t worry — Part 12 of the tutorial explains how to get round this :)

davidp November 10, 2009 at 1:46 pm

you my good sire are a genious. i’ve ticket off that “declare stage instances”, removed stage.addListener… in Main and only left addListener…, used stage.focus = game and it works now! i can’t express how happy i am right now :D

thanks again :)

Michael Williams November 10, 2009 at 1:47 pm

Haha awesome :D Great to hear that!

Navras November 24, 2009 at 3:02 am
Michael Williams November 24, 2009 at 9:37 am

Whoops! Thanks, Navras, I had the wrong link up there. Correct link is http://gamedev.michaeljameswilliams.com/downloads/tutorials/AvoiderGame/part2/AvoiderGame-part2.zip.

I’ve corrected it now, cheers for that :)

Elie December 4, 2009 at 12:08 pm

Hi Mike,

So far I understood everything except when you created a custom event.
Can you please elaborate the following:
“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. “

Thank You,
Keep up the great tutorials,

.-= Elie´s last blog: RSS Feeds now available =-.

Michael Williams December 4, 2009 at 12:33 pm

Hey Elie,

Have you checked out my post, Extends, Override and Super? I think it’ll help out :)

Michael Joseph Wojnar March 2, 2010 at 12:00 am

Wow, I just realized that you and I have the same initials. o_O

Michael Williams March 20, 2010 at 11:20 am

@MJW: Spooooooky…

Pete April 21, 2010 at 7:41 pm

You kind of lose me when we get to the part where start adding events through various scripts – it’s not at all clear if I’m supposed to be building a new AS script? I guess so since AvatarEvent.as is referenced later, but at that point it’s like… some of this earlier code should have gone in there, I can see a package statement further back so that implies new… I’m just getting at that it’s kinda not clear, maybe insert a “let’s create a new as file and call it AvatarEvent and now put this stuff in it) somewhere. =p

And thanks for these tutorials, part 1 alone cleared up so much confusion and so many questions I had – I also HATE the gui and the timeline, so just using the gui to set up library bits and do a little drawing, and leaving the rest to separate scripts, this is EXACTLY what I needed. Thanks!

Michael Williams April 23, 2010 at 1:34 pm

Hey Pete,

I lose a lot of people at that point :/

Thanks for the tip — I think that will help clear it up a lot! Very useful idea :) I’ve added, “Start a new AS file, AvatarEvent.as” to the A Grand Event section, does that help?

Thanks for your kind words :)

rimacy@yahoo.com May 4, 2010 at 5:16 pm

super is losing me and I checked out your post and am Still Lost (blush) would you draw me a picture of what is going on in the game when we use super?

Michael Williams May 7, 2010 at 8:13 pm

Hey rimacy,

Let me try without a picture. It’s easier to explain something by finding out either (a) what you’re trying to do with super(), or (b) what’s not “clicking” (i.e. what’s not making sense). So, let me know the answer to (a) or (b) :)

ayumilove May 7, 2010 at 10:44 pm

@ rimacy

Its very simple, don’t need a picture.
Just remember that super is to call the parent’s method or parent’s variable.
Place this in the back of you mind.

Here is some food for thought:
If I have a class called BasketBall extends Ball.
The Ball is the parent while BasketBall is the child.

When to use super()?
We use super when we need to pass some variable from
the child to the parent to store them. Instead of making
class variable in child, we use the parent’s variable to store them instead.

Also, if we were to override the parent’s function with something
else AND we wanted to also do the parent’s function implementation,
we will override the function, place the child’s implementation,
and then call the parent’s method to do the rest.

public class BasketBall extends Ball
{
public override function bounce () : void
{
//trace(“Bounce up 5 meters high when it hits the ground”);
super.bounce();
}
}

public class Ball
{
public function bounce () : void
{
trace(“Make noise when it hits the floor”);
}
}

the trace result would be :-
Bounce up 5 meters high when it hits the ground
Make noise when it hits the floor

It does BasketBall implementation first (bounce up 5 meters)
then Ball implementation (make noise)

rimacy@yahoo.com May 8, 2010 at 12:57 am

Thanks Michael Williams AND Aiyumilove for your responses, I’m now getting what super is at close range(using functions or variables of the parent….right?) but the big picture is eluding me. What is it doing in in the custom event in the avoider game???

ayumilove May 8, 2010 at 1:22 am

public function AvatarEvent( type:String )
        {
            super( type );
        }

you mean this?
I have already explained above.
As you can see in the AvatarEvent Class which extends Event.
AvatarEvent is the child while Event is the parent.
The child does not have a variable to store the type.
Therefore, it uses the parent’s variable to store the type.

When the addEventListener catches an event from the
particular object that it is listening, it looks into the parent’s
event type. And if it matches with the CustomEvent ID (the type)
which is AvatarEvent.DEAD (the type must be a string value),
then it triggers the method assigned in addEventListener
to perform a specific job.

var avatar : Avatar = new Avatar ();
avatar.addEventListener (AvatarEvent.DEAD, doSomething);

The avatar is the instance that has an addEventListener placed on.
Any event dispatched by avatar instance AND if it matches
AvatarEvent.DEAD, run the method called doSomething();

ayumilove May 8, 2010 at 1:29 am

Therefore, it uses the parent’s variable to store the type.

Correction:
The AvatarEvent Class uses the parent’s constructor to pass an argument/parameter
of the value “type”.

When the parent constructor is called, the parent
will take that value and stores it into its own variable.

rimacy@yahoo.com May 8, 2010 at 1:52 am

Thanks You Guys!!!!
Cheers,

Rob

rimacy@yahoo.com May 8, 2010 at 1:57 am

Our AvatarEvent is using it’s parent’s(Event) type function!!

Michael Williams May 10, 2010 at 7:05 pm

You got it, rimacy! Great explanations, ayumilove — thanks for helping out :)

Tom May 12, 2010 at 3:44 am

For some reason the game stops after running the avatar into an enemy, it’s like before I added the GameOverScreen, I’ve checked over all the code, and I even downloaded your code to paste over what i had written. It was the same. Any suggestions?

ayumilove May 13, 2010 at 12:12 am

You could send your source code to me to check :)
or
use Michael William’s guide to debugging to see how to narrow things down.

http://gamedev.michaeljameswilliams.com/2009/05/02/fix-any-bug-solo/

Crump May 16, 2010 at 12:47 pm

Just to see if I’ve understood the super(type) correctly…
It basicly pulls through the actions of the Event class, to find out what it has to do with the sort of type that we passed?
Another thing.. (damn, am I feeling stupid :( )

I need a simple explanation on how we go from the AvatarEvent back to DocumentClass
I mean, our PlayScreen calls the AvatarEvent when you hit an enemy, how does it go from the AvatarEvent, back to the DocumentClass?

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: