AS3 Avoider Game Tutorial, Part 5: A Score and a Clock

by Michael James Williams on February 3, 2009 · 327 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 add a score and a clock, to give the player some mark of their skills. It’s a long part, but there’s a part in the middle that’s a good point for you to break off and come back later, if you don’t feel like doing the whole thing now.

Click the image below to see the result of this part in action:

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.

Everything Counts

When you think about it, a clock and a score are basically the same thing. Each contains a number — a count of either time passed or points scored — and each provides a visual representation of that number — whether it’s a simple piece of text, an animated stopwatch or a growing progress bar.

If we made a Clock class and a Score class, they would therefore both contain a variable, of type Number, for storing time passed or points scored.

They’d also both need to have three functions in common:

  1. addToValue( amountToAdd:Number ) — we’d run this every tick, or every time the player did something worthy of some points
  2. reset() — this would set the score/time to its original value (i.e., zero); we’d run this when the score/timer was created, but we might alsouse this to reset the time if the player grabbed a certain power up, or remove all the player’s points if he hit an enemy
  3. updateDisplay() — this would make the visual representation show the current value of the score/time, so we’d probably run this every time the value was changed

What they probably won’t have in common is the visual display. This means that the way the updateDisplay() function actually works is likely to be different, too. Does this mean we have to write two separate classes?

No.

We’ve used the extends keyword quite a few times throughout this project, but only ever regarding a built-in class like MovieClip or Event. Now we’re going to use it to extend a class that we’ll write ourselves.

Here’s the idea:

  • We’ll start with a class that contains everything a Clock and a Score has in common — let’s call this class Counter. This will have no visual element, because we’re never actually going to use it.
  • We’ll extend Counter to make a second class, Score, that does have a suitable visual element.
  • Finally, we’ll extend Counter once more to make a third class, Clock that has a different visual element.

Make sense? OK, let’s do it.

Learning to Count… Again

Based on the above, here’s a base for the Counter class:

?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
package
{
	import flash.display.MovieClip;
	public class Counter extends MovieClip
	{
		public var currentValue:Number;
 
		public function Counter()
		{
 
		}
 
		public function addToValue( amountToAdd:Number ):void
		{
 
		}
 
		public function reset():void
		{
 
		}
 
		public function updateDisplay():void
		{
 
		}
	}
}

Save this new ActionScript file as Counter.as in your Classes directory. I expect you understand it all, so I won’t go through the whole thing. I’d like to draw attention to that extends MovieClip, though. Since MovieClips can contain other displayable objects, this part lets Counter contain displayable objects. (We could use a class like Sprite or DisplayObjectContainer to achieve this, but using MovieClip lets us create the actual Clock and Score objects in Flash, rather than having to draw everything using code.)

You might be wondering why Counter needs to extend MovieClip if Counter itself isn’t going to contain any visual objects. The reason is that a class can’t extend two separate classes at once. If we don’t let Counter extend MovieClip, then Clock and Score won’t be able to extend MovieClip either. We’re just planning ahead based on what we know we’re going to do next.

Let’s make these functions actually do something. First, reset(). It’s pretty obvious what that needs to do:

?View Code ACTIONSCRIPT3
18
19
20
21
public function reset():void
{
	currentValue = 0;
}

addToValue() is pretty obvious, too:

?View Code ACTIONSCRIPT3
13
14
15
16
public function addToValue( amountToAdd:Number ):void
{
	currentValue = currentValue + amountToAdd;
}

I said above that we’d reset() when the score/time was created, so let’s call reset() within the constructor:

?View Code ACTIONSCRIPT3
8
9
10
11
public function Counter()
{
	reset();
}

Finally, and again as mentioned above, we’ll need to update the display every time the internal value is changed. Since that’s only done in the reset() and addToValue() functions, let’s run updateDisplay() from inside those:

?View Code ACTIONSCRIPT3
13
14
15
16
17
18
19
20
21
22
23
public function addToValue( amountToAdd:Number ):void
{
	currentValue = currentValue + amountToAdd;
	updateDisplay();
}
 
public function reset():void
{
	currentValue = 0;
	updateDisplay();
}

It seems kind of strange to run a function that does absolutely nothing, but once more we’re just planning ahead.

Draw the Score

This idea of extending a custom class can be tricky to understand without a concrete example. If you’re finding it confusing, bear with me while we build something with it and I think it will become clear.

Time to do something in Flash itself now. Switch back to the FLA file and Insert a New Symbol. Call it Score and make it a Movie clip. In the Linkage options, export it for ActionScript and give it a class name of Score.

When you click OK, you’ll be in Edit mode for the Score movie clip. (Remember you can get into this mode at any point by right-clicking the Score item in the Library and selecting Edit.)

To keep things straightforward, I’m just going to use a simple piece of text that displays a number for the score:

screenshot

Nothing fancy. I’ve just typed a random number in there to see what it looks like, by the way, there’s no significance to 834.

We’re going to need to be able to edit that number using code, of course. Normal text doesn’t allow this, so we need to change it to Dynamic Text. Do you remember, back in Part 3, I told you to change the Game Over text to Static Text? Well, now we need to do the opposite.

Select the text, then, in the Properties panel, click the drop-down list (shown below) to Dynamic Text:

screenshot

When you deselect the text, it’ll have a dotted border around it:

screenshot

We also need to give the text a name by which we can refer to it in code (its instance name), just as we gave the Start and Restart buttons their own instance names in Part 4. I’ll call it scoreDisplay.

screenshot

Oh, one annoying thing Flash does with dynamic text is it makes it selectable by default, so the players mouse cursor turns into a text cursor when they mouse over it. If you want to get rid of this behaviour (and most people do), just select the text, find the little button that says “Ab” on it, and click it so that it’s not “sticking out”:

screenshot

Feel free to make this look a bit prettier. Add a border, or draw some stars around it, or whatever. Just make sure you’ve got an instance of dynamic text with the name scoreDisplay. I’m going to put a label on mine:

screenshot

(Note that I’ve made the label’s text static rather than dynamic, because I don’t ever need to change it.)

OK, that’s enough of that. Time for some code!

It’s Got its Mother’s Functions, and its Father’s Variables

Start a new AS file, call it Score.as and put it in the Classes directory. Here’s the code to go inside. Note that line 3 imports the TextField class we need because of the dynamic text. Are you getting tired of Flash not knowing all that by default yet?

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

At first glance, this seems a bit odd. Why aren’t we typing in the currentValue variable, or the addToValue() function? Well, we don’t need to; that extends keyword means they’re already there. So, if you were to create an instance of the Score class, you’d be able to run .reset(). You can also access reset() from within the Score() constructor, if you like.

This is called inheritance, and is very powerful. By letting Score extend Counter, we’ve given it every public variable and function that Counter had. The only exception is the constructor… sort of.

Score() doesn’t automatically inherit the contents of the Counter() constructor function. Obviously this could be pretty annoying, since chances are we want Score() to do everything Counter() does, plus perhaps a little more on top. We don’t have to copy and paste the contents of Counter(), though — this is where super comes in.

We used super before, when creating a custom class, but I didn’t explain what it did. It’s actually quite simple; it allows a class to access the functions of the class that it extends. Again, an example should help. Simply change the Score() constructor like so:

?View Code ACTIONSCRIPT3
6
7
8
9
public function Score()
{
	super();
}

Here, super() is running all the code from the Counter() constructor (so in this case, it’s just running reset()).

Alright, so, safe in the knowledge that we’ve already written the code to handle addToValue() and reset(), let’s work on updateDisplay().

There’s a slight problem, though. Like I said, the function updateDisplay() already exists in Score because it already exists in Counter. If we just write:

?View Code ACTIONSCRIPT3
11
12
13
14
public function updateDisplay():void
{
 
}

then Flash will give us an error, because there’ll be two functions called updateDisplay() within one class, and that’s not allowed.

There’s a simple solution to this, too, though: the override keyword. All we have to do is prefix the line declaring the function with it, like this:

?View Code ACTIONSCRIPT3
11
12
13
14
override public function updateDisplay():void
{
 
}

There’s a slight catch, though. By overriding the function, we’ve lost all the contents, just as we did with the constructor — in a way, every class’s constructor overrides the constructor of the class it extends. This isn’t a problem to us right now, because Counter’s updateDisplay() function doesn’t do anything at the minute. But if we want to, say, make it check whether the value had changed since the last time it had updated the display and only update if so (to increase efficiency), we’d have to copy and paste that code into every class that extends Counter.

Except of course we don’t because we can use super again. Like this:

?View Code ACTIONSCRIPT3
11
12
13
14
override public function updateDisplay():void
{
	super.updateDisplay();
}

Now any code that’s in Counter’s updateDisplay() function will run when Score’s updateDisplay() function is run. If you’re still unclear on how override and super work, check out my post on the subject.

At last, we’re ready to write some new code. It’s so simple, too:

?View Code ACTIONSCRIPT3
11
12
13
14
15
override public function updateDisplay():void
{
	super.updateDisplay();
	scoreDisplay.text = currentValue.toString();
}

That’s pretty straightforward, apart from .toString(). Programmers call any sequence of letters and numbers a string, because they’re a string of characters. The .text property of scoreDisplay is a string, so it needs a string value passed to it. currentValue isn’t a string, though; we defined it as a Number. Fortunately, all Numbers have a function called toString() that returns the number in string form.

Hmm… I guess that wasn’t so straightforward after all.

Time to put our score in the game.

(By the way, if you’re low on time, this is the great point at which to stop and come back later that I mentioned at the start of the post.)

The Scores on the Doors

I guess we could place the score display in the game using code in AvoiderGame, like we’re doing with the Avatar and the enemies, but that’s going to be a pain so let’s do it the way we’ve done buttons. Edit the PlayScreen movie clip (in the library) and drag the Score movie clip onto it in a suitable location:

screenshot

We’ll need to give this an instance name, too. Select it, and in the appropriate field in the Properties panel, enter gameScore. (I’ve called it this so as not to confuse it with scoreDisplay, the name of the text field within the movie clip.)

If you save and run the game (Control > Test Movie), it’ll look like this:

screenshot

It’s not increasing, because we haven’t run addToValue() ever. But note that it says “Score: 0″ and not “Score: 834″. This is because its constructor function has been run automatically, which in turn has run reset().

It’s up to you how you want the player to earn points. I’m going to keep things very simple and just make the score increase by ten every time an enemy appears on-screen. I do this in AvoiderGame.as:

?View Code ACTIONSCRIPT3
31
32
33
34
35
36
37
38
39
40
public function onTick( timerEvent:TimerEvent ):void 
{
	if ( Math.random() < 0.1 )
	{
		var randomX:Number = Math.random() * 400;
		var newEnemy:Enemy = new Enemy( randomX, -15 );
		army.push( newEnemy );
		addChild( newEnemy );
		gameScore.addToValue( 10 );
	}

(Line 39 is the new one.) Result:

screenshot

(Note: I’ve heard that this isn’t working in Flash Pro CS5. If you can’t see the score, try editing your Score symbol, selecting the text field, and embedding the font (there’s a button for that). Just embed all the numbers.)

(Reader Mac gave this suggestion in the comments: “Those using flash pro cs5 and having problem with the dynamic text field, disable the “auto-kern” option from the text properties to make it appear on the stage.” Thanks, Mac!)

This is actually starting to feel like a game now :) We really need the score to be displayed on the game over screen though. Otherwise, what’s the point? Or, as the player will be asking, “what’re the points?” … I think that’s a really funny joke. You can tell your friends, if you like.

We could put another instance of Score on the GameOverScreen, but that’s really wasteful, since we’re only going to change it once, and don’t need any of the functions we’ve built in to it. Let’s just use another dynamic text field instead. Edit the GameOverScreen movie clip from the library, and add a new dynamic text field:

screenshot

(As you can see, I’ve also added a new label, and I’ve moved the restart button.)

Give your score field an instance name of finalScore, so that we can set it using code.

How are we going to get the final score from the play screen to the game over screen? Well, the best place to do this transfer is the document class. That’s its job, really, to manage the different screens. And the best place within the document class is the onAvatarDeath() function. Open up DocumentClass.as. Here’s how I’d like it to look (lines 21 and 27 are new):

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

In line 19, we grab the final score from the play screen, and in line 28 we feed it into the game over screen. We haven’t written either of the functions necessary yet, but change onAvatarDeath() as above, anyway, and then we’ll add these new functions in.

For playScreen.getFinalScore(), switch back to AvoiderGame.as. All we need is a new function like the following:

?View Code ACTIONSCRIPT3
55
56
57
58
public function getFinalScore():Number
{
	return gameScore.currentValue;
}

This is getting the current score directly from the Score instance. A little dodgy, I suppose, since we might decide later to have updateDisplay() to show the score as being five times the internal value, and then .currentValue would be incorrect — but I don’t think we need to worry for now.

Now, for gameOverScreen.setFinalScore( finalScore ), open GameOverScreen.as. First thing’s first; import the TextField class:

?View Code ACTIONSCRIPT3
1
2
3
4
5
6
package 
{
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
	import flash.events.MouseEvent;
	import flash.text.TextField;

Now, the new setFinalScore() function we’re going to write is almost exactly the same as updateDisplay() from the Score class, except it accepts a parameter:

?View Code ACTIONSCRIPT3
20
21
22
23
public function setFinalScore( scoreValue:Number ):void
{
	finalScore.text = scoreValue.toString();
}

Save it and run it. Of course, you’ll have to hit an enemy before you see the result:

screenshot

Great! Eight or nine years ago, that would have made the front page of Newgrounds like a shot.

Goodness, is That the Time?

I’ll admit, it seems to have taken a long time just to get the score in the game. But, actually, a lot of that was setting up the Counter (which doesn’t need doing again) and explaining the idea of inheritance. Writing the Clock’s code won’t take long at all, and it’ll be pretty easy.

This time, let’s not use a numeric display. I want to show you why we’re bothering with all this extending and overriding and so forth. We’re going to use an animation instead.

Switch back to the FLA and create a new movie clip (Insert > New Symbol) called Stopwatch. This time, don’t export it for ActionScript or define a class. This is just going to be the animation we use within the actual Clock movie clip.

Make sure you’re editing the new movie clip, and draw a stopwatch (well, you can draw whatever you like, but I’m drawing a stopwatch):

screenshot

Now, you remember in Part 4, when we were creating the buttons, we added new keyframes for each state of the button? We need to do the same here, except each new keyframe will be a new frame of the animation. (If you’re comfortable with using Flash as an animation tool, feel free to throw in some tweens or whatever you want here.) Right-click Frame 2 and select Insert Keyframe:

screenshot

Make some change that indicates the passage of time:

screenshot

Keep adding new frames until your animation can loop back on itself. (You can always just use a two-frame animation if you like; a digital clock blinking “12:00″ might be quite funny.)

We’re going to use this animation within the Clock in much the same way as we use the dynamic text field within the Score. Create another new movie clip and call it Clock. This time, we do want to export it for ActionScript; keep the class’s name as Clock.

Make sure you’re editing the Clock movie clip, then drag the Stopwatch animation from the library. It needs an instance name: call it clockDisplay. You can add a label or other decoration if you like. So, the Clock movie clip is what will go into the playScreen movie clip, and will contain and control the Stopwatch movie clip.

Next, create a new AS file, and save it as Clock.as in the Classes folder. Here’s the contents:

?View Code ACTIONSCRIPT3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package
{
	import flash.display.MovieClip;
	public class Clock extends Counter
	{
		public function Clock()
		{
			super();
		}
 
		override public function updateDisplay():void
		{
			super.updateDisplay();
 
		}
	}
}

It’s almost identical to how we started with Score.as, except we’re importing MovieClip rather than TextField.

This time, we need the updateDisplay() function to move to the correct frame of the animation. The function we need for this is called gotoAndStop(). To switch the animation to frame 3, for instance, we would call:

?View Code ACTIONSCRIPT3
clockDisplay.gotoAndStop( 3 );

The problem is, we’re going to update the clock’s internal value every tick. The way I plan to do this is to add the number of milliseconds in a tick (25) every time the onTick() function is run. This means that if we just run clockDisplay.gotoAndStop( currentValue ), then it’ll play frame 25, then frame 50, then frame 75… skipping out all the frames in-between. Plus, after a couple of seconds it’ll be looking for frame 2000 — and I don’t know about you, but I ran out of patience at frame 12.

So we need to do two things:

  1. Divide currentValue by another number to get the actual frame to play, in order to avoid skipping over frames
  2. Go back to the first frame once we go past the last frame

With those points in mind, here’s my updateDisplay() function:

?View Code ACTIONSCRIPT3
11
12
13
14
15
16
17
18
19
20
21
22
23
override public function updateDisplay():void
{
	super.updateDisplay();
 
	var frameToSkipTo:Number = currentValue / 1000;
	frameToSkipTo = Math.floor( frameToSkipTo );
	frameToSkipTo = frameToSkipTo + 1;
	if ( frameToSkipTo > 12 )
	{
		frameToSkipTo = frameToSkipTo - 12;
	}
	clockDisplay.gotoAndStop( frameToSkipTo );
}

I’ll go through it:

  • Line 15 creates a new variable, frameToSkipTo, which divides the internal value by 1000 in order to convert the number of milliseconds passed to the number of seconds passed
  • Line 16 uses a function I’ve not mentioned before, Math.floor(), which rounds the number down to the nearest whole number
  • Line 17 adds 1, because otherwise the first frame the code would attempt to play is frame 0, which doesn’t exist (first frame is frame 1)
  • Lines 18-20 checks to see if the new frame is after my last frame (I have 12 frames). If it is, it subtracts 12, so 13 -> 1, 14 -> 2, etc
  • Line 21 moves the animation to the required frame

Actually this isn’t quite right. It works for almost two and a half seconds then stops. Why? It’s because after that, frameToSkipTo is 25 or more, and so subtracting 12 just makes it 13 or more — and there aren’t 13 frames!

To fix this, we’ll simply switch the if for a while (line 18):

?View Code ACTIONSCRIPT3
11
12
13
14
15
16
17
18
19
20
21
22
23
override public function updateDisplay():void
{
	super.updateDisplay();
 
	var frameToSkipTo:Number = currentValue / 1000;
	frameToSkipTo = Math.floor( frameToSkipTo );
	frameToSkipTo = frameToSkipTo + 1;
	while ( frameToSkipTo > 12 )
	{
		frameToSkipTo = frameToSkipTo - 12;
	}
	clockDisplay.gotoAndStop( frameToSkipTo );
}

A while is like an if, except it runs over and over again until the condition within the brackets is no longer true. So, when frameToSkipTo reaches 25, the while will detect that it’s more than 12, and subtract 12, making it 13. The while will then again detect that it’s more than 12, and subtract another lot of 12, making it 1.

Simple! Feel free to alter any of this function to suit your own animation.

Wrapping Up

I could walk you through adding the Clock to the AvoiderGame, then writing the code to add 25 to the clock every tick, and pass the data back through to the GameOverScreen, and so on. But I’m not going to.

If I did, I’d be repeating myself, because it’s almost exactly the same as what we did for the score. Also, because there are no new concepts to introduce, I think it’ll be more useful for you to have a go yourself, rather than just follow exactly what I say.

Hope you don’t think this is a cop-out. If you get stuck, post a comment below, send me an email, or download the zip of the files I’ve been working on and take a look at what I did.

Good luck!

In the next part (available here) we’ll do a bunch of small changes based on suggestions other people have given. The week after that, we’ll add keyboard control.

Thanks for reading :)

{ 326 comments… read them below or add one }

us01 May 1, 2011 at 1:08 am

Everything has been going ok for me. But now i have this error upon trying part 5.

H:\Documents and Settings\Owner\Desktop\DeliverTheHolyBurger\Classes\Counter.as, Line 25 1046: Type was not found or was not a compile-time constant: Void.

Are you still alive?

us01 May 1, 2011 at 1:31 am

Oh look… i typed Void and not void…, found a few other misspellings here and there too including a ; that i didnt put in where needed.

I think that was the only problem… But i decided before finding those mentioned errors above, because of not being able to find what was wrong… I used your code instead and now its giving me errors about your ZIPed code that is different from the tutorial code…

H:\Documents and Settings\Owner\Desktop\DeliverTheHolyBurger\Classes\DeliverTheHolyBurger.as, Line 63 1120: Access of undefined property gameClock.
H:\Documents and Settings\Owner\Desktop\DeliverTheHolyBurger\Classes\DeliverTheHolyBurger.as, Line 33 1120: Access of undefined property gameClock.

Did you add a new symbol in the fla? Please help is so needed.

Because i added your code from ZIP now im not sure what it was i added…

Tim May 10, 2011 at 11:29 am

Hey Michael! Thanks for the nice tutorials =) but I have a bit of a problem, I get an error when I put this in ;gameScore.addToValue( 10 );
I have done everything you say in the tutorial but I still get this goddamn error; 1220 Access of undefined property gameScore

Please help me, I need this for a really important school project!
Thanks! =)

Jim May 21, 2011 at 4:30 am

@ US01 It sounds like your problem is you never named the movie clip instance of the clock that you dragged out onto the playscreen =)

@Tim same thing for you my friend, go into the playscreen click on the movie clip of the game score, go to properties tab and name the instance to gameScore =)

Also for anyone having trouble getting their score to actually display.. I ran into some troubles when using the static text method when creating the Score movieclip so what i tried and happen to work for me was switching it to TLF Text and in the drop-box below it select “editable” and it should work.. did for me anyway =)

Great tutorial btw!
Thanks

Tim May 31, 2011 at 2:59 am

I can’t figure out this problem… It occurred somewhere around adding a score display. I keep getting a message that i need to embed some text. I thought i fixed it but now my start button doesn’t work. Are they connected in some weird way or have I made some mistakes… Thanks in advance for any answers

Q Smith June 3, 2011 at 8:29 pm

With the score display (on Flash CS5.5), the only way I could get it to work is to do the same thing as the buttons in the last tutorial. ((If there is a better way, please tell me, but your way didn’t work.))

public var gameScore:Score;

    public function AvoiderGame()
    {
        //Score set up
        gameScore = new Score();
        gameScore.x = 543.20;
        gameScore.y = 8.5;
        addChild(gameScore);

Someone June 9, 2011 at 2:42 pm

I’m using CS5.5 and when I typed “834″ in the scoreDisplay dynamic text, it only showed numbers 8, 3 or 4. For example when I had 35 points it would only show Score: 3. Then I left scoreDisplay empty, and the scoreDisplay worked correctly.

Maybe somekind of new feature?

kman June 9, 2011 at 3:32 pm

hey michael, my score seems to be only flashing from 3 – 5 – 7 -9 and back to 3… it flashes really slow as well :S ? any reasons ?

Joey Clover June 10, 2011 at 11:54 am

@the guys above

Check the width/height/max chars of the textfield. Also, in the code, you can always set textFieldName.autoSize = TextFieldAutoSize.CENTER; or something :)

kman June 12, 2011 at 5:03 am

haha ok cheers mate, i actually set it to TLF text and it works but sometimes it doesnt ? :S

Joey Clover June 12, 2011 at 11:12 am

@kman Well, I never use TLF text, I use classic as it works just as well and isn’t confusing ;)

kman June 14, 2011 at 7:33 am

@Joey Clover, hey its maybe because im using cs 5.5 (only avaialable version) but i tried dynamic text for myscore and it says ” Fonts should be embedded for any text that may be edited at runtime, other than text with the “Use Device Fonts” setting. Use the Text > Font Embedding command to embed fonts. ” … and it doesnt even launch the game now :( .. but TLF works on another computer >_< help please !

kman June 14, 2011 at 8:03 am

i embed ALL the fonts.. now it doesnt even do anything… no warnings watsoever just a blank white screen when i test the movie sigh

Joey Clover June 14, 2011 at 8:22 am

Embedded ALL the fonts? :o
Only embed the ONE font you need, it was probably not loading because you embedded so many texts. Just embed the fonts and characters you need. Do not embed all character. Just 0-9 and A-Z :)

kman June 14, 2011 at 1:44 pm

yeah true, thanks alot for ur help man, it works at home and i hope it works tommorow at uni ! maybe its got to do with the uni computers, their internet and their cs 5 flash

fabrizio June 17, 2011 at 2:06 pm

hi Michael!
first of all i want to tell you how good is in my opinion your site and your tutorials, always so clear and interestings!
after that, I wanted to ask you a sudgestion because I’m having troubles with making work the counter of the points and I really can’t understard why..
When I download your zipped lessons files and I try the game it works well with the score that increase regulary.
But when I open your FLA file and I try (without change anything) to test the movie, the new clip created has got a counter that doesen’t work. The number of the score is a casual number the sometimes appear and sometimes disappear…
What could be the problem?? I really can’t understand!!
fabrizio

Michael James Williams June 17, 2011 at 7:48 pm

Hey, thanks Fabrizio! Hmm, it’s possible that my FLA has some issues with your version of Flash Pro; I wrote it a couple years ago, so it’s getting a bit out of date now. Otherwise, try changing the font of my counter, and embedding the font in the FLA (I explain this in a later part of the series, I think).

fabrizio June 18, 2011 at 3:47 pm

Omg, thank you very much Michael..You can’t understand how I’m glad that now the counter works well!!! I was suffering since days for this problem!! You are right,it was only a font problem, I solved it embedding the fonts..
Thank you!!

Kai July 4, 2011 at 8:45 pm

If scoreDisplay is set to classic text and dynamic the game will work, but
If scoreDisplay is set to TLF text and editable, flash somehow wont recognize it and throws erro #1009 Cannot access a property or method of a null object reference.
Do you happen to know why that is?

best regards,
Kai

ExplosionsHurt July 9, 2011 at 12:48 am

I’ve been having a problem with the textbox. It flashes different numbers, like 3 and 5, and really slow as well.

For some reason, the problem is not there if I use TLF Text.

Any suggestions?

Melon Bomb July 16, 2011 at 3:45 am

(Why does moderation take too long).
Can anybody help? I’m trying this tutorial and the only problem is getting the clock to move, Stopwatch is in Clock with 12 frames of motion and an instance of clockDisplay but the clock doesn’t play, I changed gotoAndStop to a number between 1 and 12 to test but it’s like it does not reach it, please help, I’d appreciate it.

Angela July 26, 2011 at 7:26 pm

If you’re using CS5 and its not displaying the score, the workaround provided by “Someone” from 6/8/2011 for CS5.5 works, too:
“Then I left scoreDisplay empty, and the scoreDisplay worked correctly.”
FYI – I’m using Classic Text, Dynamic Text, and also I had to embed the text.

David Phillips August 13, 2011 at 2:09 am

I am having the exact same problem as Melon Bomb. I have done the “Is it that Time” part of this series multiple times and each time I get a timer that doesn’t move to any frame. I feel as though I have tired everything. Worst of all it all makes sense and the tutorials files work when downloaded. I’ve checked mine against the working one multiple time and it all seems the same! Could anyone please explain more in-depth anything related to setting up the movie clip or the code that drives it?? Thanks

David Phillips August 13, 2011 at 3:58 am

Disregard that last comment, even though i feel like i tried this multiple times my error was… gameClock.addToValue( 25 ); in the on tick function. I had errors with the addToValue but it fixed it when i changed the instance name of the clock on the play screen to gameClock.

Bobby August 17, 2011 at 8:54 pm

Hi Michael,

These tutorials are awesome. I’m learning a lot here. I just can’t get the clock work… went through the tutorial for the third time and here’s the thing: the clock doesn’t move. There is no error message.

Here’s what I found out

In the Counter class, under updateDisplay function, currentValue variable traces as it supposed to.
In the Clock class it traces as “0″, frameToSkipTo traces as “1″ never changing.

What could be wrong? My Clock class just in case:

package  {

import flash.display.MovieClip;

public class Clock extends Counter {

public function Clock() 
{
    // constructor code
    super();
}

override public function updateDisplay():void
{
    super.updateDisplay();

    var frameToSkipTo:Number = currentValue / 1000;

    frameToSkipTo = Math.floor( frameToSkipTo);
    frameToSkipTo = frameToSkipTo + 1;

    while (frameToSkipTo &gt; 12)
    {
        frameToSkipTo = frameToSkipTo - 12;
    }
    clockDisplay.gotoAndStop(frameToSkipTo);

    trace ("frameToSkipTo ", frameToSkipTo)
    trace (currentValue)
}

}

}

MelonBomb August 27, 2011 at 11:25 pm

I actually fixed it by changing the 1000 variable to a lesser number.

ExplosionsHurt September 7, 2011 at 7:54 am

Turns out that it seems to work if you turn anti-aliasing off on the text fields. A temporary solution, for now…

Anyway, wouldn’t it be better to have a clock image, and an arrow on top of it, and change the arrows rotation so that we get smooth clocks?

Mick3y September 11, 2011 at 2:15 pm

I just started coding and have gotten the hang of it slightly; im still having an issue with the score… here is my code:

package
{
    import flash.display.MovieClip;
    public class Counter extends MovieClip
    {
        public var currentValue:Number;

    public function Counter()
    {
        reset();
    }

public function addToValue( amountToAdd:Number ):void
{
    currentValue = currentValue + amountToAdd;
    updateDisplay();
}

public function reset():void
{
    currentValue = 0;
    updateDisplay();
}

public function updateDisplay():void
{
    super.updateDisplay();
    scoreDisplay.text = currentValue.toString();
}

}

Im getting an error code that says “1120: Access of undefined property scoreDisplay.”

I need some help bad

Thx

Period Three September 14, 2011 at 6:04 am

@ Bobby Did you add “clockDisplay.addToValue( 25 );” to your onTick function in AvoiderGame.as?

side note: I passed a value of 5 instead of 25 to make it complete a 12 frame loop every minute so I could add a minute counter above the clock and then report the player’s time in minutes and seconds on the gameOverScreen. I wanted to add 1 to a clockTimer var each time it looped, so I had to change the while ( frameToSkipTo > 12 ) back to an if() and just subtract 12000 from currentValue. A nice benefit to this method is that it leaves a remainder that can easily be converted to seconds.

Period Three September 15, 2011 at 8:20 pm

@Mick3y

When you created the dynamic text field for the score, did you give it an instance name of scoreDisplay?

Pan Optik October 6, 2011 at 2:28 pm

Hy guys.
here it is how i would like to use the clock and the score:
-at five established clock appointment the level change each time,and the end of last level is the game over
-but for each x number (score) of enemies you get back time and can turn back to the previous level

could you give me an hand to traduce this into code?
Thank you for support!!

paulo October 10, 2011 at 10:44 am

i’m using cs5,i allredy embeded the numbers but it doesnt display the score???wat shud i do???

paulo October 10, 2011 at 11:24 am

it displays nothing…

Kevin October 10, 2011 at 7:01 pm

I saw the note about this not working in cs5. I had to add public var gameScore:Score; in my document class and embed the font I was using to get the score to work properly. I haven’t done the clock yet but it seems as if cs5 does not automatically create variables for you and you’ll need to do it anyway(I’ve done this tutorial several times)

Also if you use the number 834 in your dynamic text box you’ll only get the numbers 834 in the movie clip unless you either embed all numeric symbols OR change the text box to 0123456789

_TAPE November 1, 2011 at 5:54 pm

I sometimes receive this output message when my avatar hit the enemy.

TypeError: Error #1009: Cannot access a property or method of a null object reference.
    at Main/onPlayerDeath()
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at PlayScreen/onTick()
    at flash.utils::Timer/_timerDispatch()
    at flash.utils::Timer/tick()

how to fix this?

Kcrik November 4, 2011 at 3:18 pm

Can you copy paste the code in your onPlayerDeath() function ?

Rapahelle November 7, 2011 at 12:48 pm

hey I like your tutorial but there are some problem that I cant fix, and I guess some people here have the same problem, I put the score on the main .as file, I guess
it didn't recognise the textbox that I insert which is the scoreDisplay(Instance Name)
Im using cs5.5
I hope somebody can help me. thanks in advance.

Rapahelle November 7, 2011 at 12:48 pm

hey I like your tutorial but there are some problem that I cant fix, and I guess some people here have the same problem, I put the score on the main .as file, I guess
it didn’t recognise the textbox that I insert which is the scoreDisplay(Instance Name)
Im using cs5.5
I hope somebody can help me. thanks in advance.

Joe November 26, 2011 at 1:34 am

I think some people are having a similar problem I was having with the score using a newer version of flash like CS 5.5. When you start the game, if the score is not there or it stays at “0,” and/or you get this message,
“Fonts should be embedded for any text that may be edited at runtime, other than text with the “Use Device Fonts” setting. Use the Text > Font Embedding command to embed fonts.”
Try this:
-Select your score text box
-Under Properties, in the Character tab, look for the “anti-alias” drop down menu
-Select “Use Device Fonts”
-Save all and Run

Patrick December 3, 2011 at 3:09 am

This was a great part to the tutorial. I followed it up to the section “The Scores on the Doors” before I wanted to do something different.
You mentioned that you didn’t want to hard code the text in because it would be slightly more difficult.
I’m curious though as to how to do this though.
I would have thought this would have worked:

public var font:Font;
public var format:TextFormat;
public var scoreDisplay:TextField;

    public function Score()
    {
        super();

    font = new Font(); //from library
    format = new TextFormat();
    format.font = font.fontName;
    format.color = 0x000000;
    format.size = 26;
    format.letterSpacing = 2;

    scoreDisplay = new TextField();
    scoreDisplay.embedFonts = true;
    scoreDisplay.antiAliasType = AntiAliasType.ADVANCED;
    scoreDisplay.autoSize = TextFieldAutoSize.LEFT;
    scoreDisplay.selectable = false;
    //scoreDisplay.x = 300;
    //scoreDisplay.y = 300;
    scoreDisplay.defaultTextFormat = format;
    scoreDisplay.text = "Score "+currentValue.toString();
    addChild(scoreDisplay);
}

The error displayed is: Cannot access a property or method of a null object reference.

I know it isn’t a problem with font embedding.

Is it just that scoreDisplay should be created in AvoiderGame or Counter?

James Ebert December 4, 2011 at 12:13 pm

I’ve gotten as far as getting the score up but when I run the game the score only displays “NaN”. I’ve embedded the font, I’ve made sure the text is dynamic, I’ve tried adding in the “score” variable (it didn’t change anything so i took it back out). I couldn’t find anyone else who’s come across this same issue so if any one has any suggestions please let me know.

James Ebert December 4, 2011 at 2:24 pm

I don’t know if this is a normal fix for my problem but i added “= 0;” to the line “public var currentValue:Number;” in the counter.as. as soon as I did that the score generated correctly.

Stephen December 31, 2011 at 6:37 am

What do i do? I get this:

C:\Users\Stephen\Desktop\AvoiderGame.as, Line 62 1120: Access of undefined property gameClock.

wheneever I try to run the game D: idk how to fix D: help pls?

Mac January 17, 2012 at 9:04 am

Those using flash pro cs5 and having problem with the dynamic text field, disable the “auto-kern” option from the text properties to make it appear on the stage..

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

Awesome, thanks Mac. I’ve added your tip to the tutorial.

alex57834 February 8, 2012 at 5:31 pm

I have got a problem I am up to to the scores on the doors part and it has a error saying

ReferenceError: Error #1065: Variable TCMText is not defined. in the output and in the complier errors box it says that in the score class line 15 1078 label must be simple identifier.
Any help would be great

Luchong February 19, 2012 at 4:13 am

I really dont get why you didn’t write like this:

 public function onAvatarDeath( avatarEvent:AvatarEvent ):void
{
    var finalScore:Number = playScreen.getFinalScore();

gameOverScreen = new GameOverScreen();
gameOverScreen.addEventListener( NavigationEvent.RESTART, onRequestRestart );
gameOverScreen.x = 0;
gameOverScreen.y = 0;
gameOverScreen.setFinalScore( finalScore );
addChild( gameOverScreen );

playScreen = null;

}

Luchong February 19, 2012 at 4:14 am

Sorry, like this:

public function onAvatarDeath( avatarEvent:AvatarEvent ):void
{
var finalScore:Number = playScreen.getFinalScore();

gameOverScreen = new GameOverScreen();
gameOverScreen.addEventListener( NavigationEvent.RESTART, onRequestRestart );
gameOverScreen.x = 0;
gameOverScreen.y = 0;
gameOverScreen.gameScore.finalScore.text = playScreen.scoreDisplay.text
addChild( gameOverScreen );

playScreen = null;

}

Lai March 30, 2012 at 3:48 am

i wanna ask about gameScore…
i using flash CS5.5 and
i already set the instance name to gameScore movieClip.
and also scoreDisplay for dynamic text.
but got error in AvoidGame.as,
said that “undefined property gameScore”
how to solve this ??
hope can replay as soon as possible… Thank you…

TJ April 17, 2012 at 2:58 pm

My game won’t let me use Counter a the base class. I have copied all of your code. I still have undefined propertioes of gameClock and gameScore.

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

{ 1 trackback }

Previous post:

Next post: