Blog

Kenney
Spaceship Tutorial Part 3: Making enemies
April 13th, 2010

In this part of the tutorial we’re gonna add enemies to our game to shoot at, this is going to be tricky so be prepared and make sure you read the previous parts first!

Spaceship3

If you haven’t read the previous parts first, go ahead and read part 1 and part 2 of the tutorial to learn how to create and move the spaceship and make it shoot.

Step 1. Making the enemy

Like in the first few parts of the tutorial we’re going to draw our object first. So go ahead and draw a nice looking enemy spaceship. Here’s mine:

If you’ve done that, select the enemy and hit F8. In the new window tick MovieClip and press OK. Now go ahead and delete the MovieClip like we did with the bullet. Again, it’s still in the library just not on the stage anymore but that’s okay – we’re going to create the enemies dynamicly.

Hit CTRL + L (on Windows) to open the Library of your project which shows you the elements in your document, the enemy ship should be there!

Step 2. Linking the enemy

In the Library, select the enemy spaceship and right click it. In the menu select “Linkage…” (or “Properties…” if you’re using Adobe Flash CS4 or up).

In the new window tick “Export for ActionScript” which unlocks the ability to give the MovieClip an identifier. Insert “enemy”, now hit “OK” and close the library.

Step 3. Coding part 1

This is probably going to be the most advanced and difficult code of the whole project so take your time, read it slowly and try to imagine what every line of code says in normal English.

First, let’s place the following code on the main timeline. What that is? Basicly you click somewhere on the stage (not on any object, so clicking the background is fine) and press F9 to bring up the code panel – then, place your code there. If you then create the Flash file (CTRL + ENTER, remember?) you should see no errors if you did it right.

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
i = 0;
enemies = [];
 
spawnEnemy = function(){
	_root.attachMovie("enemy", "enemy"+i, _root.getNextHighestDepth());
	_root["enemy"+i]._x = random(Stage.width);
	_root["enemy"+i]._y = 0;
	enemies.push("enemy"+i);
 
	_root["enemy"+i].onEnterFrame = function(){
		this._y += 3;
		if(this._y > Stage.height){
			for(e = 0; e < _root.enemies.length; e++){
				if(_root.enemies[e] == this._name){
					_root.enemies.splice(e, 1);
				}
			}
 
			this.removeMovieClip();
		}
	}
 
	i++;
}
 
enemy_interval = setInterval(spawnEnemy, 2000);

Alright, the explanation of the above code:

1
2
i = 0;
enemies = [];

First we make a new variable named i and set it to 0, this is going to be used to make sure our enemies all have an unique name. Then we make a new array (which basicly is a package of variables) to store all the enemy names.

1
spawnEnemy = function(){

Create a new function, functions are blocks of code that can simply be reused by calling the function name (so calling spawnEnemy() would execute all the following code).

1
_root.attachMovie("enemy", "enemy"+i, _root.getNextHighestDepth());

Just like in the part of the tutorial about the bullets we’re going to attach the enemy spaceship from the library to the stage. Give it an unique name (for example, enemy1 or enemy10) and make sure the depth is the next on the stage with _root.getNextHighestDepth().

1
2
_root["enemy"+i]._x = random(Stage.width);
_root["enemy"+i]._y = 0;

Now set the X position of the newly created enemy to a random position with a maximum of the total width of the stage. Then set the Y position to 0, the top of the screen.

1
enemies.push("enemy"+i);

Now add the enemy name (ex. enemy1) to the enemies array we created earlier which should look like this now: enemies = ["enemy1"];.

1
_root["enemy"+i].onEnterFrame = function(){

Now make sure the enemy executes the following code every frame…

1
this._y += 3;

Add 3 pixels to the Y position which makes the enemy spaceship move down, towards the player.

1
if(this._y > Stage.height){

But if the Y position is larger than the total height of the stage (so if the enemy has left the stage…)

1
for(e = 0; e < _root.enemies.length; e++){

Do a loop. A loop goes through a number of values and then executes functions like removing an enemy from an array (which we’re about to do!).

1
if(_root.enemies[e] == this._name){

Ah! So if the value in the array is exactly the same (==) as the name of the enemy then remove it. Because, once the enemy has left the stage we have no use for it anymore and we might aswell remove it from the array to save CPU power.

1
_root.enemies.splice(e, 1);

Splice removes items from an array, so “e” is the position of the loop and the exact name of the enemy (checked for that above) and 1 means that 1 item is going to be removed. Putting a 2 there would make Flash remove the 2 following items, but we don’t want that now.

1
this.removeMovieClip();

Then we close some open functions and to removeMovieClip which does that it says, removes a MovieClip from the stage (the enemy that has left the stage).

1
i++;

Now close some more open functions and add 1 (++ is the same as += 1) to the i value to make sure the next enemy has an unique name (ex. enemy2).

1
enemy_interval = setInterval(spawnEnemy, 2000);

Last but not least we make an interval. Intervals execute a function every X seconds (2000 milliseconds in this case). So Flash is going to create a new enemy every 2000 milliseconds, you can lower the number to create more enemies every two seconds.

Step 4. Coding part 2

Okay, now for the next code you have to seek the code for the bullets to be created which is on the player MovieClip. So go ahead and click the player (spaceship) and hit F9 to open the coding panel again.

You can now see this code:

1
2
3
4
5
6
_root["bullet"+i].onEnterFrame = function(){
	this._y -= 10;
	if(this._y < -30){
		this.removeMovieClip();
	}
}

Replace it with:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
_root["bullet"+i].onEnterFrame = function(){
	this._y -= 10;
	if(this._y < -30){
		this.removeMovieClip();
	}
 
	for(k = 0; k < _root.enemies.length; k++){
		if(this.hitTest(_root[_root.enemies[k]])){
			this.removeMovieClip();
			_root[_root.enemies[k]].removeMovieClip();
			_root.enemies.splice(k, 1);
		}
	}
}

Okay, don’t worry about this code being difficult – we learned all functions and methods above, so it’s kind of an exam, see if you’ve learned something :) Let’s check what the code means line by line:

1
2
3
4
5
_root["bullet"+i].onEnterFrame = function(){
	this._y -= 10;
	if(this._y < -30){
		this.removeMovieClip();
	}

This is old code so I’m going to skip that, you should already know what this means ;)

1
for(k = 0; k < _root.enemies.length; k++){

Make a new loop and loop through the enemy array like before.

1
if(this.hitTest(_root[_root.enemies[k]])){

If a bullet hits one of the entries in the enemies array (so, if a bullet hits an enemy…)

1
2
this.removeMovieClip();
_root[_root.enemies[k]].removeMovieClip();

Then remove the bullet AND the enemy.

1
_root.enemies.splice(k, 1);

And remove the enemy that has been hit from the enemies array.

Step 5. Testing and finishing

Now press CTRL + ENTER to test the game, you should be able to shoot bullets and hit enemies. If you had any problems feel free to ask questions below, if you want a sample download the source file here:

Source
Source

Up next we’re going to add scoring and lives and a game over screen!

comment
Replies

Robert says:

hey i like how you did this spaceship
but by the time i got to the end of third part
it is giving me errors
the errors look like this “Statement must appear within on/onClipEvent handler”
so whats going on can you help me out

Kenney says:

Hm, well that sounds like you’ve placed your code at the wrong place. Make sure that code that starts with onClipEvent(load) or onClipEvent(enterFrame) is placed ON a MovieClip (click the MovieClip and hit F9 to enter code) and not on a frame.

Robert says:

im pretty sure im putting the code in the right spot because my frame doesnt have the a for action on top of it

Robert says:

lol nvm it turns out i was putting the code in the wrong place thanks for the help

Robert says:

okay after i fixed the code placing and i tested the movie when i tried to shoot the laser it didnt work

Jc says:

Yeah the part 3!!

Miles says:

I get all of the enemies staying at the top of the screen until it crashes

Kenney says:

Sounds like there’s something wrong with the loop to generate new enemies Miles. When a loop has no end it’s going to crash Flash, if the enemies don’t move then the code to make them move hasn’t been added to the newly created enemies.

igor says:

Nice tutorials kenney :)
Can’t wait for the next one(s).

adam says:

my game is very addicting cant wait for scoring and lives

Ben says:

When I shoot, my bullets dont effect the enemy, and my ship keeps on popping to where it started. I probably messed up on the coding. Heres what my coding looks like.

onClipEvent(load){
timer = 0;
i = 0;
}

onClipEvent(enterFrame){
if(timer > 0){
timer–;
}

if(Key.isDown(Key.LEFT)){
_x -= 6;
}else if(Key.isDown(Key.RIGHT)){
_x += 6;
}

if(Key.isDown(Key.SPACE)){
if(timer == 0){
_root.attachMovie(“bullet”, “bullet”+i, _root.getNextHighestDepth());
_root["bullet"+i]._x = _x;
_root["bullet"+i]._y = _y-20;

_root["bullet"+i].onEnterFrame = function(){
this._y -= 10;
if(this._y < -30){
this.removeMovieClip();
}

for(k = 0; k < _root.enemies.length; k++){
if(this.hitTest(_root[_root.enemies[k]])){
this.removeMovieClip();
_root[_root.enemies[k]].removeMovieClip();
_root.enemies.splice(k, 1);
}
}
}

i++;
timer = 20;
}
}
}

Ben says:

Disreguard that last statement, I fixed the problem

adam says:

when is the next tutorial going to be done

Kenney says:

@Adam, when it’s finished ;)

aaron says:

When i test my movie everything seems to work fine but when i shoot the bullets the enemies just go away without the bullet hitting them.

thiaguera says:

Did I miss any part about keeping the spaceship within the screen?

Kenney says:

Nope, never described that. But with the knowledge you gained from the tutorials, you can figure that out :)

thor says:

hey cant wait till the next tutorial (this one is great) do you know when it is coming out

thiaguera says:

I`m a lazy MuckerFother… great tutorial by the way.

billy says:

umm…. could you possibly give me the code early for the hittest to have your player die. I am making this for an assignment for web design. i have everything but this hittest. i have score and menu buttons.

billy says:

aaron if you read this, the problem is the bounding boxes. a way to fix this somewhat is to make the code:

if(this.hitTest(_root[_root.enemies[k]]._x,_root[_root.enemies[k]]._y,true)){

this makes your bullet hit but misses around the edges near the top and bottom.

billy says:

ok. new problem. i figured out the hittest but i want to have the enemies stop coming at me but to restart when you click Play again. Can you help kenny?

Kenney says:

To stop the enemies from coming you can use:
clearInterval(enemy_interval);

and to make them start appearing again:
enemy_interval = setInterval(spawnEnemy, 2000);

MarkSpizer says:

great post as usual!

Hazzard says:

Thanks Kenny ! you rock !
These tutorials are perfect , Thanks for taking the time to do this and explain all the coding step by step. I’ve been looking at other tutorials during my flash learning process and they never go into the detail that you do .
Looking forward to Part 4 :)

yevonne says:

when will the next tutorial be done

thiaguera says:

Hi, again.
What do I do to avoid the enemies to spawn almost outside the stage width?
Thanks!

thiaguera says:

Nevermind… I figured it out myself. Now I´m trying to make the enemies shoot at me.

bernie says:

when are you gonna finish the tutorial on how to make the enemy fight back and maybe a points screen

Kenney says:

Scoring, lives and a game over screen will be covered in the next tutorial and no, I don’t know when that’ll be done since I do these in my spare time.

adam says:

hey i was just wondering if the next tutorial is almost done?(sorry if i sound pushy. not trying to) ;]

ha5an says:

Very good tutorial, please his permission to be placed on my blog that can be applied by my students, I wait for the next tutorial and success always Kenney, thanks

Kenney says:

Yeah sure, you can place it just make sure you give proper credit to who wrote it :)

deven says:

when is the next tutorial going to be done

sam says:

is the next one coming soon? plus when the enemies are destroyed, how do i make them explode?

nicole says:

how to you make the enemies blow up?

santa's big helpers says:

ben and all everyone else! try this to use on for your spaceship!

i found something else useful!! replace the code for your spaceship with this instead:

onClipEvent(load){
timer = 0;
i = 0;
}

onClipEvent(enterFrame){
if(timer > 0){
timer–;
}

if (Key.isDown(Key.RIGHT)) {
//this will move 10 units to the right
this._x += 10;
} else if (Key.isDown(Key.LEFT)) {
//this will move 10 units to the right
this._x -= 10;
} else if (Key.isDown(Key.UP)) {
//this will move 10 units up
this._y -= 10;
} else if (Key.isDown(Key.DOWN)) {
//this will move 15 units down
this._y += 15;
}

if(Key.isDown(Key.SPACE)){
if(timer == 0){
_root.attachMovie(“bullet”, “bullet”+i, _root.getNextHighestDepth());
_root["bullet"+i]._x = _x;
_root["bullet"+i]._y = _y-20;

_root["bullet"+i].onEnterFrame = function(){
this._y -= 10;
if(this._y < -30){
this.removeMovieClip();
}
}

i++;
timer = 20;
}
}
}

i hope it helps you guys!
(also use the auto format to clean it up!)

santa's big helpers says:

the above code lets you move left,right up and down hope i helped you all!

santa's big helpers says:

as well as shoot with the spacebar!

gerald says:

have’nt you done with the 3rd tutorial?

gerald says:

I want to put levels on my game, how is that?

gerald says:

I want my enemies to shoot hows that?

Kenney says:

Read the second part of the tutorial to learn how to make enemies shoot.

Kaplan84 says:

Thanks alot! this is really cool.
Iv’e added a second player and made each of them shoot two shots.

For the second bullet, add a new object, identical to the bullet but with a different name. It’ll need a new timer and a new counter variable.

onClipEvent (load) {
timer = 0;
i = 0;
timer1 = 0;
j = 0;

Right after the bullet part, add this (still under KeyisDown(Key.SPACE):
if (timer1 == 0) {
_root.attachMovie(“bullet1″,”bullet1″+j,_root.getNextHighestDepth());
_root["bullet1"+j]._x = _x+53;
_root["bullet1"+j]._y = _y-43;
_root["bullet1"+j].onEnterFrame = function() {

this._y -= 10;
if (this._y<-70) {
this.removeMovieClip();
}
}
}

j++;
timer1 = 20;
}
}
}

For the second player, simply add another ship as written and copy the first player's script with different keys. Type "flash keycode" into google to find the ones you need. I used a,d,w,s for movement and q to shoot. So it looks like this:
if (Key.isDown(65)) {
_x -= 6;
} else if (Key.isDown(68)) {
_x += 6;
} else if (Key.isDown(87)) {
_y -= 6;
} else if (Key.isDown(83)) {
_y += 6;
} if (Key.isDown(81)) {
if (timer == 0) {

You'll need to add seperate objects for the bullets.

michael says:

When will the next part of the tutorial be posted

michael says:

by the way great tutorials

S.H. says:

Is the fourth part out yet?

walden329 says:

.,can you please add it now..please..i want the game over and live sessionzz..please post it now..

Kenney says:

It has been posted ages ago! http://www.kenney.nl/?cat=4



Leave a Reply