Create A Simple Catch Game Part 1

Get Adobe Flash player

Today we lay the foundation for a simple Catch Game where objects fall and you catch them with another object. In this tutorial we will create the objects and make them fall as well as declare the types of objects they are so that we have more options for when we catch them. Catching and scoring will be covered in Part 2 of this tutorial.

Description:
This is Part 1 of a series of tutorials designed at teaching the fundamentals of object oriented programming by creating a simple Flash game that uses one object controlled by the mouse to catch other objects that appear to be falling from the sky.

You can either download the completed example , or start from scratch. Its up to you.

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

Prerequisites :
OOP & The Document Class. If you have not read my tutorial on using the document class, and or if you are not familiar with document classes in general then you should read this prior to continuing.

Level:
Beginner / Intermediate

If you read my tutorial on OOP & The document Class then you have covered the very basic use of a document class and creating objects from a blueprint or Class. We are now going to take that a step further and create a document class for a game and also create game objects from the library of the FLA by extending library items as Classes. We will then explore a method of accessing objects by type in order to cast it into something we need.

1. Create a new AS3 Flash File.
2. Create a symbol of something good (I’ve used the iA logo, but you can use a primary colored circle for now), hit F8. Name it Good_1 and make sure that it is exported for AS and that a Class definition has been created.

Figure 1

Figure 1

3. Repeat this process for Good_2( I have just duplicated another logo, but you could create a second primary colored circle), Bad_1 and Bad_2 movie clips making sure that they are all exported for AS as in Figure 1 above. I’ve drawn a simple skull in the spirit of Halloween.

Figure 2

Your library should look like Figure 2 above

But what you draw and animate depends on your concept. If you have been using primary colored circles for Good, then perhaps you could use secondary colored squares for “Bad” and you could make a learning game.

Ultimately your graphics will have to do with the concept of the game and the game play, but for now just having two different object types that we can Identify later on is key to our customization. We will cover creating game concepts, creating artwork, hit detection, mouse movement and more in Part 2 of this tutorial.

4. Finally we need to create the object that will catch the falling objects. This will be called catchObject. Create a basket shaped object and make it a movie clip called catchObject. Export it for ActionScript as you did for the falling objects.

5. In the properties window, type Catchgame in the document class field.

6. Delete anything left over on your layer, name it AS3 and lock it.
5. Save your file as catchgame.fla
6. Create a new AS3 Document File. File>New>ActionScript File.
7. Create a package for your game, and name it Catchgame.as.
8. Type in the following code:

  1. package{
  2.  
  3. // imports
  4. import flash.display.*;
  5. import flash.events.*;
  6. import flash.utils.Timer;
  7. import flash.utils.getDefinitionByName;
  8.  
  9. // class
  10. public class Catchgame extends MovieClip {
  11.  // set up variables
  12.              // set up timer to drop objects
  13.   var nextObject:Timer;
  14.   // create objects array
  15.   var objects:Array = new Array();
  16.   // set speed
  17.   const speed:Number = 7.0;
  18.  
  19.  
  20.  public function Catchgame() {
  21.  // constructor
  22.  
  23.  
  24.   }// end constructor
  25.  
  26.  
  27.  
  28.  }; // end class
  29.  
  30. }// end package

Lines 4 and 5 are standard imports. Line 6 imports a Timer that is used to fire off a function every so often and Line 7 imports getDefinitionByName, which we’ll get to later. For now lets just get it imported.

On Line 10 we set up our class which is our game class. We’ll extend Movie Clip as all we need is a timeline. This is also where we will set up our variables.

Line 13 is nextObject Timer which will be the pace of how fast things drop. Line 15 is an array of objects and Line 17 is the speed of which our items will fall.

9. While still in our AS3 Document File, add the following code on Line 26.

  1.  public function startGame() {
  2.    setNextObject();
  3.   addEventListener(Event.ENTER_FRAME, moveObject);
  4.   addEventListener(MouseEvent.CLICK, onClick);
  5.   }
  6.  
  7.   public function setNextObject():void {
  8.  nextObject = new Timer(1000, 1);
  9.  nextObject.addEventListener(TimerEvent.TIMER_COMPLETE, newObject);
  10.  nextObject.start();  
  11.   }

On Line 26 we write the function startGame(). This will fire off when it receives input from the start game button, which we will do next. But for now lets finish reviewing the startGame() and the setNextObject() functions.

startGame() calls a function called setNextObject(), adds an ENTER_FRAME event to the stage for animation and score updating and adds a listener to the stage to listen for user clicks.

The function setNextObject is called when the game begins. This starts a new instance of the Timer Class and every 1000 milliseconds (or 1 second) it will fire off the newObject() function.

Lets create the Start Button now.

10. Go back to your FLA and create a start game button. I’ve used a VCR component from the video components.
11. Make it a MovieClip.
12. Drag it on the stage and name it startBtn in the properties window as well.
13. Window>Actions (or option-F9) to get your actionscript panel up. Type the following on Frame 1 of the AS3 layer you created earlier.

  1.  startBtn.addEventListener(MouseEvent.CLICK, startIt);
  2.  
  3. function startIt(e:MouseEvent):void {
  4.  startGame()
  5.  startBtn.visible = false;
  6.  startBtn.removeEventListener(MouseEvent.CLICK, startIt);
  7. }

Ok, keep in mind I’m not exactly setting up my event listeners for optimum garbage removal. This certainly isn’t great practice, but thats ok, I assume you will incorporate garbage removal where needed.

14.Go back to Catchgame.as file and around Line 38 add the newObject() function which we called earlier.

  1. public function newObject(e:TimerEvent) {
  2.    //create next object
  3.    // array of good and bad objects
  4.    var badObjects:Array = ["Bad_1", "Bad_2"]
  5.    var goodObjects:Array = ["Good_1", "Good_2"]
  6.    // create random number
  7.    if (Math.random() < .5 ) {
  8.     //based of good object length
  9.     var r:int = Math.floor(Math.random()*goodObjects.length);
  10.     // get the good object by name and cast it as its own class in a temporary variable
  11.     var classRef:Class = getDefinitionByName(goodObjects[r]) as Class;
  12.     // now we can make a new version of the class
  13.     var newObject:MovieClip = new classRef();
  14.     // dynamic var (because mc is an object) typestr it as good
  15.     newObject.typestr = "good";
  16.    } else {
  17.     //  for bad objects see comments above
  18.     r = Math.floor(Math.random()*badObjects.length);
  19.     var classRef:Class = getDefinitionByName(badObjects[r]) as Class;
  20.     var newObject:MovieClip = new classRef();
  21.     // typestr it bad
  22.     newObject.typestr = "bad";
  23.    }
  24.    // random pos
  25.    newObject.x = Math.random()* 600;
  26.    newObject.scaleX = newObject.scaleY = .4;
  27.    addChild(newObject);
  28.    // push it to array
  29.    objects.push(newObject);
  30.    // create another one
  31.    setNextObject();
  32.    
  33.   }
  34.  
  35.  public function moveObject(e:Event):void {
  36.   // cycle thru objects
  37.   for (var i:int=objects.length-1; i>=0; i–) {
  38.    //move objects down based on speed
  39.    objects[i].y += speed;
  40.    objects[i].rotation += speed;
  41.    // if objects leaves the stage
  42.    if (objects[i].y > 400) {
  43.     // remove it from display list
  44.     removeChild(objects[i]);
  45.     // remove it from the array backwards
  46.     // remove it backwards removes all problems when looping through.
  47.     // forward would cause confusion if you removed 5 before 4.
  48.     objects.splice(i, 1);
  49.        
  50.    }
  51.   }
  52.  }
  53. }

Lets cover the two functions we’ve just added which are pretty much the same two functions we have to write any time we do a code-based particle effect or animated game. One function is used to create the objects and one function to move them. If you did my confetti animation tutorial in you probably remember we did the same thing there. Instantiate in one function, then move with an ENTER_FRAME event. Eventually we’ll need a function to remove these items as well. But that is down the road.

newObject() Function: Timer Event. This basically will create the objects over time.
Line 41: create an array of strings for the bad objects. These strings need to match the name of your movie clip.
Line 42: create an array of strings for the good objects. Also need to match the names of your bad objects in your library.
Line 44: create an if statement that that fires off 50% of the time (see random number).
Line 46: if(<.5): create a temp var that creates a random number based on the length of the good items array.
Line 48: if(<.5):get the good object by name (the string in the array) and cast it as its own class in a temporary variable. (This is the reason we imported the getDefinitionByName earlier. ). This is the technique we use to get a movie clip out of the library and cast as a dynamic object.

getDefinitionByName()
This is a nifty little trick I learned from Gary Rosenzweig at Flash Game University. There he shows you how to create an array of strings and use those strings to instantiate movie clips out of the library and finally to put dynamic variables on them. In fact most of what you are seeing in this tutorial I learned from Gary. In the second part of this I will branch off and show you some stuff Gary doesn’t cover. Gary’s site is a companion to a must have book for aspiring game developers in my opinion, ActionScript 3.0 Game Programming University.

Line 50: if(<.5):Cast as a Movie Clip.
Line 52: if(<.5): add a dynamic variable to the MC.typestr "good".
Line 53-59: else: Pick a bad object, and follow the same procedural as the if statement except we will typestr it as “bad”.
Line 62: randomly position the object on screen regardless of whether it is good or bad.
Line 63: scale the object 40% (my drawings are large, you may not need to do this).
Line 64: add the Object to the stage.
Line 66: add the Object to the OBJECT array.

it is important to understand the differences between our arrays. We had three in total, one was an array of strings that contained the exact name of the good objects in our library. The second was another array of strings that held the exact name of the bad movie clips in the library and our third array was objects, which was created empty above the constructor and is being used to hold actual display objects. The first two arrays that were local to the mover function were simply to get the name of the objects you want to pull out of the library. The Objects array is a way of tracking all the items falling in the display list so that we can do stuff with them later…such as remove them.

Line 68: repeat the process every 1 second.

moveObject() Function: ENTER_FRAME event. This basically will move the objects continuously.

Line 82: we cycle thru the objects using a for loop.
Line 84: we move the objects y position based on the speed we set as a constant earlier.
Line 85: rotation, but certainly other properties can be added here.
Line 87: conditional statement to check if items have fallen off the stage. I’ve hard coded the stage height at 400.
Line 89: If so, remove it from the display list;
Line 90: Remove it from memory by splicing it out of the object array. Splicing takes from the back of the array, so errors aren’t caused later. Another nifty Rosenzwieg trick.

If you publish your movie you should get objects falling from the top and spinning as they fall.

Thats all we’re going to cover today. Hopefully I can finish the second part very soon so you can get your game on.

Posted on October 29, 2009 at 10:23 am by Runtime · Permalink
In: ActionScript 3, Flash, Games, OOP, Tutorial · Tagged with: , , , ,

3 Responses

Subscribe to comments via RSS

  1. Written by joanarpaivap
    on December 28, 2010 at 2:31 pm
    Permalink

    Hello

    Very good tutorial!!

    Have a second part?? I didn’t found…

  2. Written by Runtime
    on January 15, 2011 at 8:13 am
    Permalink

    Hey, thanks! Actually I do plan on writing the second part early this year.

  3. [...] of object oriented programming by creating a simple Flash game. Complete Tutorial: Part 1: Simple Catch Game I Part 2: Simple Catch Game [...]

Subscribe to comments via RSS

Leave a Reply

You must be logged in to post a comment.