RPG Programming:
by SeiferTim : 24 November 2004

Moving right along... It would be a very boring game indeed (if you could even call it a game) if your Guy could not interact with anything. So, we need to come up with some hitTests. For this simple sample game, I'm going to make some small items that the player can walk over and pick up. Nothing elaborate. First, using the same .Fla from earlier, you'll want to make a new MC, and lets name it "money". Inside, make a simple, and not to big icon for some money.

[ simple money mc ]

Now, drag an instance of this MC out to the stage, and name it "money_mc". Open up the ActionScript Pane, and enter this code:

onClipEvent (enterFrame) {
if (_root.move_mc.hitTest (this)) {
this._x = -50;
this._y = -50;
This assumes you've named the MC with the Guy MC inside it "move_mc", if you named it something else, change the code accordingly.

Essentially, what this code will do is this: Every time the Clip comes to this frame (which is always), it will check the "move_mc" movie clip against itself, and if the two touch or overlap at all, it will perform the following 3 steps: It will increase the value of "money", a variable we will be adding to "_root" by 1, then it will move this clip to the coordinates (-50,-50) - basically off the playing field so that Guy can't grab the same coin again.

When we get further along, we'll be creating items with the "duplicateMovieClip()" function, so we can later use "removeMovieClip()" to get rid of them instead of "cheating" by moving them off the screen.

We still need to do two more things before this works perfectly. First, create a new layer (you can name it ActionScript, or something if you like), select the first frame, and open up the ActionScript Panel. Enter this single line of code to create the "money" variable, with an initial value of "0":

money = 0;

Next, go back to our other Layer, and create a new TextBox, any size or color you want, and make it Dynamic. Where it says "Var:" type: "_root.money", then save and test the movie.

[ the settings for the textBox ]

Pretty simple, right? You can do much more complex things with hitTesting. For now, I would suggest getting some practice with hitTest in - it is one of the most useful functions for game programming in Flash. If you want, you can give your Guy an "HP" variable, and make a trap MC that if he steps on it, it takes away MC, or whatever. Just make sure that your Movie looks and works like the source before moving on to my next section.


Download FLA

Onwards to the next page!

page 5 of 7



kirupa.com's fast and reliable hosting provided by Media Temple.