Follow goofballgames on Twitter

How to build a tower defense flash game (Part 1 Waypoints and Enemies)

Posted by Goofball Games January - 31 - 2010 - Sunday

How to build a tower defense flash game (Part 1 – Waypoints and Enemies)

So we are going to start off strong in the first part of this tower defense tutorial “how to” series: Waypoints and Enemies.

All flash files and code can be be downloaded Here

More to the point I am going to going to show you how to have a basic enemy follow a predefined path, by following a series of waypoints. By the end of this series, you will have all the information to be well on your way to making the next great tower defense game.

A “waypoint” for the uninitiated is defined by wikipedia as a “sets of coordinates that identify a point in physical space”. I like that definition so I will use it. It basically means that our stage will be our physical space and the location of the waypoint will be defined by the it’s x,y coordinate on that stage.

We will create create a series of these waypoints all over the stage and then will make an enemy follow those waypoints to a final destination! Sounds complicated? It’s not.

So to create my first waypoint I just create a new symbol and call it “Waypoint”. The first frame will contain an image and the second frame will contain the action script line “stop();” The reason I do this is because when we are developing we may want to see the waypoints on the map, however, during the game we really don’t. this will allow us the best of both worlds.

We then take these any place them all over the map and rename the instances so we can reference them from our action script code. I did this by prefixing “wp” followed by a number to each waypoint instance name. In my example below:

So my waypoints on the stage now run all the way from “wp1” to “wp8”. If you’ve taken the liberty to actually run this code at this point, you see a whole lot of nothing, but that’s a good thing – It means you’ve done the right things :) We now have everything in place to create some movement on the screen with our first enemies.

Lets start by creating our first Creep. I’ve gone ahead and create a new symbol called “Creep” this movie clip will be the main container of all Monster/Bad Guy/Creep related images.

Now you may have noticed below in that picture I create an additional “CreepList”. Well you may be wondering what that is – If you haven’t guessed it will eventually house all the creeps inside it. Wait, did I say that Creep would house all “baddy” related images? Yes I did, therefore, “CreepList” will be contained inside the “Creep” movie clip as well.

There is an additional layer for action script that’s sole purpose is to put a “stop();” command on the first frame. In the future each additional frame will contain a new monster for each level we are on.

Ok, so now drag “Creep” somewhere off the stage for now and we have all the items in place to really start doing something.

To make things easier I am going to break up the code into three parts so all the different sets of functionality can be seen clearer. The only code I will be leaving out is the “stop();” at the top of the page and the initial call to _root.newLevel(); at the bottom. I assure you that in the zip file that I am supplying those action script piece will be in the code :) Now for the code!

So in this piece of the code we are making declarations for our initial root variables. The variable “level” will keep track of the current level we are on. The “creepCount” will keep track of the number of creeps that are currently on the screen and finally “creepArray” will actually house the movie clip information about the creep in the array.

The function newLevel initially just sets the the variables back to their default values and then uses flashes “setinterval()” to make a function call to “spawn” which is called every 5 seconds and takes in the following parameters – (level:Number, creep:Movieclip, speed:Number). The number of creeps will eventually have the potential to be a different number each time. So we call:

_root[“spawned” + _root.level] = 20;

to keep track of the of the number of keeps for a given level. Currently it’s set to 20, but later on this will be dynamic.

You can see right away in spawn that after we decrement the “spawned” counter we check to see if it is equal to 0. Meaning we have no more creeps to release on that level. This allows us send the next wave of creeps along, EVEN IF THE FIRST WAVE OF CREEPS HAVEN’T ALL FINISHED BEING SENT. That will be a powerful ability if we decide to introduce the feature to call multiple waves for a higher score.

So now we come to the meat and potatoes – How to create the damn creatures on the screen. Well it’s pretty simple in Flash, we use the “duplicateMovieClip” function. We reference the “creep1” instance we created on the stage and then create new names for these new instances. So each creep will be called “c” followed by our current ”_root.creepCount” which is always going up (ie. c1, c2, c3 … c1443)

We then take the new movie clip and we store it in our “creepArray” in the last position. This will allow us to always be able to find this whenever we need.

c.creep.gotoAndStop(_root.level);

This tells the creep what image to use and is based on the current level. New creeps images will be based on our current level (in this case we never leave level 1), so it will always look like that. If you create a new image in the “CreepList” MC and call newLevel() an additional time the picture should change as well – We’ll do that in a later in the series.

We set the x and y position of this new enemy to the current value of our first waypoint (This is where we start to tie waypoints and enemies together). The “targ” is set to the next waypoint in the list – In this case since we are setting the creeps current location to “1” the next progression would be “2”.

The creeps speed and maxspeed will be set based on the parameters I passed in during the “setInterval” and in this case is a speed of 1.5 for now. You can change it to anything you want to see what happens, make it faster or slower. The variable “rnd” will be used to add a little randomness to the creeps movement patterns – to make it look a little more natural.

Ok, so we’ve set all the variable the creep know where it is and is now on the stage – How the hell do we get to to follow the path we’ve laid out for it? Good question, it’s gonna take a little math. The good side about this type of math is that it can be used for multiple uses later on, how about the flight of the projectile, etc.

For now we need to get our creature to go in the right place.

So the first thing we want to do after we create our new “Creep” is to give him something to do each frame.

c.onEnterFrame = function ()

Everything relating in this function will be called every frame! So each frame the creep will be heading closer in the direction of the waypoint and once it gets close enough it turns its attention to the next one.

So first thing we do in lines 55 and 56 is fine where the current waypoint is and set those x and y coordinates as out “targX” and “targY” or targetX and targetY.

this.dir = Math.atan2(this.targY – this._y, this.targX – this._x) * 180 / 3.141593E+000;

The above code finds the angle between the two coordinates in degrees

this.rads = this.dir * 3.141593E+000 / 180;

Technically I could have done this in one line and not used the variable “this.dir”, however, we will need both later on. For now I only really need radians since we will be using the radians to move the creep closer t the next waypoint.

Note: 360 degrees is approx 6.283185307179586 radians

This code doesn’t currently handle any issues of rotation – All that will be handled later on in the series. It’s only a few extra lines of code, but I didn’t want to confuse the issue, so this code will just get your creep from one waypoint to the next and that’s it! I think you can appreciate that after all this.

this._x = this._x + Math.cos(this.rads) * this.speed;

bq. this._y = this._y + Math.sin(this.rads) * this.speed;

We multiple the cosine and sine of the radians and multiple by the current speed that was passed in (currently 1.5) and add them to our x and y coordinate. We are now a step closer to the waypoint.

Wait, but how do we know when we get there… Another great questions that is handles by the next few lines. We calculate the distance from the waypoint we are traveling to, to the creeps current location. If the distance falls under “5” in our case, we change our target to the next waypoint.

Viola, we are done.

So what have we learned – Just the biggies :)

  1. How to make waypoints
  2. How to create Creeps/Bad Guys/ Enemies you name it
  3. How to make the move along our predetermined path

What we still have yet to find out –

  1. How do we handle rotation so our creep if facing in the direction he/she is moving in
  2. What happens when we get to the end of the waypoints!

All these questions will be answered in the upcoming articles and more!

To go back to How to build a tower defence flash game – Intro (Intro) Click here

To continue on to Part 2 – placing Towers click here

7 Responses to “How to build a tower defense flash game (Part 1 Waypoints and Enemies)”

  1. [...] How to build a tower defense flash game – Part 1 – Waypoints and Enemies [...]

  2. [...] we begin, if you haven’t read How to build a tower defense flash game – Part 1 – Waypoints and Enemies or How to build a tower defense flash game – Part 2 – Placing Towers , you should go back [...]

  3. [...] you haven’t read How to build a tower defense flash game – Part 1 – Waypoints and Enemies, you may want to review it before you continue [...]

  4. ninja assassin says:

    I truly enjoyed reading through this write-up.Thank you.

  5. tony says:

    Thank you for sharing the info. I found the details very helpful.

  6. Roman says:

    great tut

    but you should have the code able to copy and paste it :D

  7. Roman says:

    and i have 2 errors

    on line 11 and line 49

    plz help

Leave a Reply