Create a Simple Catch Game Part 2

Get Adobe Flash player


Today we finish our catch game tutorial by adding the catch object, hit detection and a score. Catch the squares and avoid the other shapes.


Description:
This is Part 2 of a series of tutorials designed at teaching the fundamentals of object oriented programming by creating a simple Flash game.

Complete Tutorial:
Part 1: Simple Catch Game I
Part 2: Simple Catch Game II

Prerequisites :
Simple Catch Game I

Level:
Beginner to intermediate

Follow along and download the completed example , .

Our first tutorial created good and bad objects and we put a mover function on them. This time around we’ll make something to catch the good objects wit, add hit detection to the objects and the catch device. Finally we’ll track the score.

Changes were made to our Library. Instead of IA logos and skeleton heads falling as good and bad objects we’ve made shapes. Squares will be our good objects and other shapes will be our bad objects.We are creating a learning game where the user is supposed to catch only squares while various other shapes are falling.

We have also added a catch object movie clip.

Open the catchgame2.as file and lets examine the additional lines of code we’ve added since the Simple Catch Game I tutorial.

  1.             // create catcher
  2.   private var catcher:CatchObject;
  3.   // create a score
  4.   private var score:Number = 0;

Lines 19 – 23 we create a private var for the catch object and score.

Creating Classes from the Library.
In the first tutorial we explained using an array of strings to get the names of objects in the library and then using getDefinitionByName to get those movie clips out of the library and into the display list dynamically

In the libray of catchgame2.Fla Right click on the movieclip in the library named CatchObject and select properties.

This allows us to create an instance of the movie clip from the library without putting it on the stage. see line 36 of the .as file.

  1.            // add catcher
  2.   catcher = new CatchObject();
  3.   catcher.y = 320;
  4.              catcher.x = stage.stageWidth(catcher.width/2)
  5.   addChild(catcher)

We are creating the objects that fall will be handled exactly the same way using the setNextObject() function explained in Simple Catch Game I.

Moving Objects
moving the falling objects is also handled the same way as before where the ENTER_FRAME event is being added to the game using addEventListener(Event.ENTER_FRAME, moveObject) in the constructor. However within the method itself we are adding hit detection. So on every frame of the movie, we’re moving objects, checking for collisions and keeping score.

  1. i public function moveObject(e:Event):void {
  2.   // cycle thru objects
  3.   for (var i:int=objects.length-1; i>=0; i–) {
  4.    //move objects down based on speed
  5.    objects[i].y += speed;
  6.    objects[i].rotation += speed;
  7.    // if objects leaves the stage
  8.    if (objects[i].y > 400) {
  9.     // remove it from display list
  10.     removeChild(objects[i]);
  11.     // remove it from the array backwards
  12.     // remove it backwards removes all problems when looping through.
  13.     // forward would cause confusion if you removed 5 before 4.
  14.     objects.splice(i, 1);
  15.        
  16.    }
  17.    
  18.    if (objects[i].hitTestObject(catcher)) {
  19.     if (objects[i].typestr == "good") {
  20.      score += 5;
  21.     } else {
  22.      score -= 5;
  23.      if (score <= 0) {
  24.       score = 0;
  25.      }
  26.     }
  27.     removeChild(objects[i]);
  28.     objects.splice(i, 1);
  29.    }
  30.    
  31.    catcher.x = mouseX;
  32.   }
  33.   // im going to add the score
  34.   updateScore(score);
  35.  }

Hit Detection
at line 110 we add the build in hitTestObject() method of ActionScript 3. this takes one param, the object that you want to detect collision. In this case we’ll make it the catch object we instantiated in the startGame() function, catcher.

hitTestObject is a public method of the DisplayObject Class, so we can actually attach it to every falling object that we have stored in our array. As you remember from the first tutorial we created a for loop based on the length of objects in teh array to apply the speed and direction. We simply nest the conditional for hit detection inside that loop and we can access every item in the array (and subsequently its hitTestObject method in order to detect collision. So in essence each object that falls has its own listener for collision and we’ve made it listen for whether or not it collides with the catch object.

Adding A Score
Finally we’ll add a score. We created a score variable above the constructor.
Inside the mover, where the hit detection is is a great place to track the score.
Remember in the first tutorial we covered adding a temp var “typestr” to each object.
Most importantly we have a movie clip on the stage named score. This contains a dynamic text field called score_text. We will access this shortly.

Line 111: We have added a conditional based on the typestr of the object.
Line 112: We add to the score if the typestr is good.
Line 113: else if type isn’t good…
Line 114: We subtract from the score.
Line 115: We add another conditional to see if the score goes below zero, we make sure there is no negative score.
Line 119: We remove the children from the display list.
Line 120: We splice the object from the object array.
Line 123: have catcher.x be where there mouse is by accessing mouseX on the enterframe event.
Line 126: I call a new method updateScore() which takes one param, the score var we set earlier.

updateScore() can be done two ways. The Line 129 version is a bit of long hand but it helps to show the steps in which you take params, cast them as something and apply them. this function takes the score passes it to a local var s. Another temp var is created and cast as a string and finally the score is cast as a string and put inside the temp var theString. Lastly, we scope to the scoreboard movieclip which is stting on the stage. This mc has a dynamic text field inside of it called score_txt. in Line 138 we populate the text field with theScore variable.

The other version of the updateScore() method which I’ve commented out… is much simpler.
In this version we do everything in one line of code on Line 141.
We scope the score movieclip’s text field “score_txt” and there we cast the param as a string to populate it.
I’ve added this to show how you can do the same thing in one line of code.

If you run the game you will see that when you catch Squares you get a positive score and when you catch other shapes you will get points deducted from your score. Your score will never go below zero.

Pretty cool! If you notice there are two things we have not covered yet that the game does. The mouse goes away and the game ends after 10 seconds.

Hide Mouse Pointer
This is very simple actually. Like most things in AS3 its a three step process.

First we import the Flash Utils for Mouse.

  1.         import flash.ui.Mouse;

From there you can hide the mouse using the public method of the Mouse class Mouse.hide() seen on Line 34.

We can show it again when the game ends.

End Game
Ok now we’ll have to end the game. But what should constitute the end of game? Usually its a time limit. The user has a certain amount of time to catch objects and then the objects are gone. So whats the best way to go about this? Timers.

Create a Game Timer before you create the endGame function. First we’ll import the Timer.

  1.         import flash.utils.Timer;

From the startGame() function we can add a function to setup and start our game timer.

  1.  public function setGameTimer():void {
  2.  trace("GAME TIMER STARTED");
  3.  var gameTimer:Timer = new Timer(5000, 1);
  4.  gameTimer.addEventListener(TimerEvent.TIMER_COMPLETE, endGame);
  5.  gameTimer.start()
  6. }

Just like the nextObject timer we are going to listen to the completion of the event. After 5 seconds the timer will complete and the endGame function will be fired.

  1. public function endGame(e:Event):void {
  2.   trace("Game Over");
  3.   // remove all objects
  4.   for (var i:int=objects.length-1; i>=0; i–) {
  5.    removeChild(objects[i]);
  6.    objects.splice(i, 1);
  7.   }
  8.   // show mouse
  9.              Mouse.show();
  10.   removeEventListener(Event.ENTER_FRAME, moveObject);
  11.   nextObject.removeEventListener(TimerEvent.TIMER_COMPLETE, newObject);
  12.  }

Line 149 we loop through the objects array and remove all the objects on stage.
On Line 156 we show the mouse
and on Line 157 we remove the ENTER_FRAME event moveObjects. By removing this we remove our biggest CPU strain. Finally we remove the listener on nextObject which listens for the a TimerEvent before firing itself.

Well, I’ll bet you’re thinking of great game ideas using what you’ve learned in this tutorial already. There are a lot of ways you can expand upon this code. I know I have made several games using this class as a basis. Good luck!

Posted on March 28, 2011 at 3:50 pm by Runtime · Permalink
In: ActionScript 3, Flash, Games

2 Responses

Subscribe to comments via RSS

  1. Written by flipstyle79
    on February 18, 2013 at 5:50 pm
    Permalink

    I downloaded the completed template, but it gives me an error when I try to publish the FLA file: Scene 1, Layer ‘as3′, Frame 1, Line 7 1180: Call to a possibly undefined method startGame.
    Any idea why it’s doing this?

  2. Written by Runtime
    on April 6, 2013 at 6:42 pm
    Permalink

    In the Flash File, go to: File> Publish Settings > ActionScript Settings > Source Path.

    Change the folder name from “com/” to “.”

Subscribe to comments via RSS

Leave a Reply

You must be logged in to post a comment.