Blog

28
Feb
Spaceship Tutorial Part 2: Making it shoot
Tutorials

Part 2 of the tutorial on how to create a game in Flash, in this part I’ll teach you how to make the spaceship shoot bullets. Let’s get started!

Spaceship2

If you haven’t done so yet, read part 1 of the tutorial to learn how to create a spaceship and make it move. If you’ve done that, read on.

Step 1. Drawing the bullets

Start off by drawing a bullet or laser, whichever you wish. Make sure it’s facing up though! You can also use mine by downloading the source below.

If you’ve done that, select the bullet and hit F8. In the new window tick MovieClip and press OK. Now delete the MovieClip. Yes, this may sound strange but don’t worry – the MovieClip is actually still existing in your Flash document.

Hit CTRL + L to open the Library which shows you the elements in your document, the bullet should be right there!

Step 2. Linking the bullet

In the Library, select the bullet 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 “bullet”, now hit “OK” and close the library.

Step 3. Coding

Select the Spaceship MovieClip and hit F9 to open the code panel, then replace the whole code (code from part 1 should be there) with:

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
27
28
29
30
31
32
33
34
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();
				}
			}
 
			i++;
			timer = 20;
		}
	}
}

Oh God, that looks like a lot of code to explain! Indeed true, but don’t worry – it’s all rather simple :)

1
onClipEvent(load){

This tells the code that the following actions should be done when the MovieClip loads, which is a one time event.

1
2
timer = 0;
i = 0;

Creates and sets 2 variables (timer and i) to 0 for later use.

1
onClipEvent(enterFrame){

As learned in the first tutorial, the following actions are going to be repeated.

1
if(timer > 0){

If the timer variable is higher than 0…

1
timer--;

Subtract 1 (– is a different method to write -= 1) from the timer variable.

1
2
3
4
5
if(Key.isDown(Key.LEFT)){
		_x -= 6;
	}else if(Key.isDown(Key.RIGHT)){
		_x += 6;
	}

This code is already explained in the first tutorial, it makes the spaceship move left and right.

1
if(Key.isDown(Key.SPACE)){

If the spacebar is held down…

1
if(timer == 0){

And if the timer variable is exactly 0.

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

Then attach a MovieClip from the library (our bullet) to the stage, give it the name “bullet”+i (ie. bullet0) and make sure the depth is a unique number, namely the next highest depth on the stage. This is for sorting which object is on the front and which on the back.

1
_root["bullet"+i]._x = _x;

Then, locate the newly created bullet on the stage and change its X position to the X position where the code is executed – which is the spaceship.

1
_root["bullet"+i]._y = _y-20;

Also make sure the Y position of the bullet is the same as the spaceship’s but subtract 20 pixels to make sure the bullet spawns in the front of the spaceship instead of the middle.

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

The following code should repeatedly be executed ON the bullet, so essentially we’re creating code for the bullet.

1
this._y -= 10;

Constatly subtract 10 pixels from the Y position of the bullet, to make it fly up.

1
if(this._y < -30){

But if the current position of the bullet is lower than -30 (which is off the stage)…

1
this.removeMovieClip();

Then remove the MovieClip, as it has left the visible game area.

1
2
i++;
timer = 20;

Then add 1 to the i variable (to make sure the next bullet that’s going to be created has an unique name) and set the timer to 20. This makes sure you can’t shoot bullets in a stream but there are little pauses between shootings.

Step 4. Testing and finishing

Press CTRL + ENTER to test the game, you should be able to shoot bullets using the spacebar! :) If you had any problems feel free to ask questions below, if you want a sample download the source file here:

Source
Source

In the next tutorial we’re going to make enemies to shoot at!

Replies

Jc says: (reply)

Amazing, in a few steps u have a spaceship shooting bullets-
Its the easiest and best tutorial i´ve ever seen

B4rtj4h says: (reply)

Superb :p

Got my own helicopter with rockets :D

Jc says: (reply)

I made a UFO :D , I cant wait for the next part

RW says: (reply)

I’m loving you for this, can’t wait for the next episode, I’ve been searching a tutorial for adding in enemies for ages.

david says: (reply)

my spaceship is moving allright but i cant get it to shoot rockets using the spacebar

Kenney says: (reply)

@david, I can’t help you unless you describe your problem in more detail. Do you get an error? Are you 100% sure you followed all steps above exactly?

iviqrr says: (reply)

Very interesting tutorial, cant wait to try it out, but i have a suggestion, people who might not like spaceship games can change the spaceship into a vehicle (land vehicle/Sea vehicle) and change the backdrop to what they want, but thats only a suggestion ;)

Jensjo says: (reply)

Awesome, Can’t wait till the next tutorial :D

marsh says: (reply)

how long till the next tutorial

Kyle says: (reply)

sweet man u have been a great help thanks :D

adam says: (reply)

when i go to render i get a Syntax Error saying that two of my ActionScripts are used for movie clips only

billy says: (reply)

Whoo got a blob shooting lasers! Thanks!

Eric says: (reply)

Great tutorials Kenny! You make it very understandable. Any idea when the next installment will be posted? I’m looking forward to it.

Kenney says: (reply)

@Eric Really soon, it’s about halfway done.

adam says: (reply)

hope you finish your next tutorial soon. looking forward to finishing my game

SpaceKnight says: (reply)

Best Bullet-Firing Script Ever! I have written/used several others, but they do not bond with the rest of the movie very well, Well done!

... says: (reply)

Huh? (For me) The bullet spawns at the top of the screen…

me says: (reply)

THANK YOU THANK YOU THANK YOU THANK YOU SO MUCH THIS HELPED ME SO MUCH THANK YOU THANK YOU THANK YOUUUUUUUUUUU!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

me says: (reply)

sorry….

Joro67 says: (reply)

Hey, just wondering, is it possible to make two instances of the bullet appear when i hit space, just in two different places? ” Ex: Both turrets on each wing”

Thanks!

santa's big helpers says: (reply)

if you guys want to make the ship move up and down as well as left and right replace the whole code for your ship to this:

onClipEvent (enterFrame) {
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;
}
}

good luck and post a comment if this doesn’t work and i’ll try to patch it up

santa's big helpers says: (reply)

also use the autoo format button to but the coding in proper order!

santa's big helpers says: (reply)

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!

santa's big helpers says: (reply)

this code allows you yo also move up and down as well as left and right hope i helped you all!

thor says: (reply)

hi kenny,
whenever i check the code it says there is no error but when i test my movie it says there is i error like this

**Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 1: Clip events are permitted only for movie clip instances
onClipEvent(enterFrame){

Total ActionScript Errors: 1 Reported Errors: 1

thor says: (reply)

hi santa’s big helpers,
whenever i check the code its always has 5 errors
i am using macromedia flash MX 2004 pro there like this

**Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 8: Syntax error.
timer–;

**Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 11: Statement must appear within on/onClipEvent handler
if (Key.isDown(Key.RIGHT)) {

**Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 27: Syntax error.
_root.attachMovie(“bullet”, “bullet”+i, _root.getNextHighestDepth());

**Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 25: Statement must appear within on/onClipEvent handler
if(Key.isDown(Key.SPACE)){

**Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 42: Unexpected ‘}’ encountered
}

Total ActionScript Errors: 5 Reported Errors: 5

santa's big helpers says: (reply)

did you copy my code exactly?

Kenney says: (reply)

You’re placing code where you should’t place it.

gerald says: (reply)

my ship is facing right and I want to shoot bullets in a right side direction, how is that

Kenney says: (reply)

Read and understand my tutorials, I explain every line of code so you should be able to make it shoot right.

jeffaa93 says: (reply)

onClipEvent(load){
timer = 0;
i = 0;
vx = 1;
vy = 1;
}

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 += 10;
}

if (Key.isDown(Key.LEFT) && Key.isDown(Key.UP)) {
this._x -= vx;
this._y -= vy;
}
if (Key.isDown(Key.DOWN) && Key.isDown(Key.LEFT)) {
this._x -= vx;
this._y += vy;
}
if (Key.isDown(Key.UP) && Key.isDown(Key.RIGHT)) {
this._x += vx;
this._y -= vy;
}
if (Key.isDown(Key.RIGHT) && Key.isDown(Key.DOWN)) {
this._x += vx;
this._y += vy;
}

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 < 0){
this.removeMovieClip();
}
}

i++;
timer = 20;
}
}
}

This'll make the ship go diagonal too :)

Zasalamel says: (reply)

Ok,
I have a code which works fine, except for one thing
I added an extra bullet, making it fire two bullets
But….
The bullets don’t fire at the same time..
Help plz

Code::

onClipEvent(load){
timer = 0;
i = 0;
vx = 5;
vy = 5;
}

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

if (Key.isDown(Key.RIGHT)) {
this._x += 10;
}
else if (Key.isDown(Key.LEFT)) {
this._x -= 10;
}
else if (Key.isDown(Key.UP)) {
this._y -= 10;
}
else if (Key.isDown(Key.DOWN)) {
this._y += 10;
}

if (Key.isDown(Key.LEFT) && Key.isDown(Key.UP)) {
this._x -= vx;
this._y -= vy;
}
if (Key.isDown(Key.DOWN) && Key.isDown(Key.LEFT)) {
this._x -= vx;
this._y += vy;
}
if (Key.isDown(Key.UP) && Key.isDown(Key.RIGHT)) {
this._x += vx;
this._y -= vy;
}
if (Key.isDown(Key.RIGHT) && Key.isDown(Key.DOWN)) {
this._x += vx;
this._y += vy;
}

if(Key.isDown(Key.SPACE)){
if(timer == 0){
_root.attachMovie(“bullet1″, “bullet1″+i, _root.getNextHighestDepth());
_root["bullet1"+i]._x = _x+15;
_root["bullet1"+i]._y = _y;

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

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

}
}
}
}

i++;
timer = 20;
}
}
}

beginner says: (reply)

hey!
I have a little problem. My bullets spawn in the middle of the spaceship. I copied your code and I didn’t change anything but it still spawns in the middle. But it should spawn in front of my spaceship. Please help.

Anonymous says: (reply)

nothing darnng

Eber says: (reply)

I need help!!!!!!!!!!! my ship dosent shoot and i dont know what happen. i copyed the code and pasted it on the bar but still! i i dont know what u mean by subtract the one and all that.

    Kenney says: (reply)

    You aren’t supposed to copy and paste the code but read the tutorial and understand what the code says. That’s the whole point of the tutorial.

Eber says: (reply)

and btw when i click the linkage bullet, the export for action script button is not available.

Tim says: (reply)

Sorry I’m really new at this but if u don’t copy it and paste what are I suppose to do, type it by hand?

    Kenney says: (reply)

    I told you, you have to read everything and I explain everything. So you can write the coding yourself the next time, if you copy and paste and have no clue what the code actually says it’s never going to work.

Rohan says: (reply)

I am doing it horizontally, so… I can’t get the code to work… help pls?

bloom says: (reply)

awesome, thanx alot

chen says: (reply)

hey uhm what movieclip u mention to delete?:/ which one

Kenney says: (reply)

The MovieClip you just created, just hit DEL after you’ve created it.

cory brandstetter says: (reply)

hey when i typed the code for making it shoot it won’t shoot i mean it gives some bullshit error that says Clip events are permitted only for movie clip instances for both the load and the enter frame. and please don’t say that i have to read the tuterial and understand i mean that is just a bullshit exuse so you won’t have to answer. tell me what is wrong and tell me how to fix it please email me at (brandstc2929@yahoo.ca)

Kenney says: (reply)

First, calm down with the swearing. Jeez! Okay, when it says that it means you’re probably using ActionScript 3.0 while this code is intended for ActionScript 2.0. Make sure you’re working on an ActionScript 2.0 project by entering the Publish settings of your project.

Chobit says: (reply)

Hehe, here I am again ^^ Is there any part 3 yet? on part 1 there is a “click here to get to part 2″ link. But here it is no such link to part 3, if I am right.

Kenney says: (reply)

You can see part 1 to 4 here: http://www.kenney.nl/?cat=4

mike says: (reply)

I typed the code line by line understanding what it says, but when i fire my bullet the bullet fires from the boarder of the blue box of the rocket. and im not too sure how to change it so it fires from the middle.
please help
thankyou

mike says: (reply)

Sorry for double posting, but never mind that question. i figured it out =]

LAURA says: (reply)

@Kennedy, you said that the code is for action script 2.0. Well, I am using 2.0..I have also typed the codes correctly and did not miss any step. I have gone through your codes and the steps more than 20 times, yet, there is always an erroe at the shooting part.The error says:
**Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 1: Clip events are permitted only for movie clip instances
onClipEvent(load){

**Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 7: Clip events are permitted only for movie clip instances
onClipEvent(enterFrame){

Total ActionScript Errors: 2 Reported Errors: 2

Could you please help me on this part?
I really don’t understand what I have done wrong?

LAURA says: (reply)

@Kenney, I am using Action script 2.0. Have also gone through your tuitorial ,ore than 20 times. Codes snd steps seem to match yours but I stiill find errors when I’m about to run it. This is the error:
Please please help me.
**Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 1: Clip events are permitted only for movie clip instances
onClipEvent(load){

**Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 7: Clip events are permitted only for movie clip instances
onClipEvent(enterFrame){

Total ActionScript Errors: 2 Reported Errors: 2

John says: (reply)

I have the same error too

LAURA says: (reply)

@Kenny, I’m sooo sorry for the trouble. Your code seem to work just right. I had placed the code in the wrong place :)
Thank you soooo much. Great job out there!

Adam says: (reply)

Great tutorial. I managed to create a 3d looking spaceship with bullet firing. If any of you can’t find part 3. search ‘spaceship game’ in the search bar of this website. You should see part 3 & 4

Reginork says: (reply)

For anyone who truly wants to learn flash code write everything out by hand first. Then you can look it up with out changing screens. Thanks Kenny.

Kenney says: (reply)

Glad you liked it :)

Kurato says: (reply)

Im currently having a problem similar to someone above. I made my aircraft capable of turning and flying in any direction (code). But I don’t know how to make the bullet shoot where the plane is facing. X/Y + x factor not the best solution can you help me code? I dont want the bullet just fly in the direction im facing, the bullet also have to face the same direction (e.g like the lazer in your game, the bullet isn’t a round object). so far, all the tutorial I found is click in that direction, I intend to make a 1-2 players game so mouse is not an option :( .
Im also intend to make missle, do you know how to code changing weapon? ktybye :)

onClipEvent(load){
timer = 0;
i = 0
thrust = 1;
maxSpeed = 40;
decay = .95;
}

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

if (Key.isDown(Key.RIGHT)) {
_rotation += 5;
}
if (Key.isDown(Key.LEFT)) {
_rotation -= 5;
}
//
//
if (Key.isDown(Key.UP)) {
// calculate speed and trajectory based on rotation
xSpeed += thrust*Math.sin(_rotation*(Math.PI/180));
ySpeed += thrust*Math.cos(_rotation*(Math.PI/180));
flames._visible = true;
flames_small._visible = false;
} else {
// deccelerate when Up Arrow key is released
xSpeed *= decay;
ySpeed *= decay;
flames._visible = false;
flames_small._visible = true;
}
}
onClipEvent (enterFrame) {
if (Key.isDown(Key.DOWN)) {
// calculate speed and trajectory based on rotation
xSpeed -= Decay*Math.sin(_rotation*(Math.PI/180));
ySpeed -= Decay*Math.cos(_rotation*(Math.PI/180));
}
//
// maintain speed limit
speed = Math.sqrt((xSpeed*xSpeed)+(ySpeed*ySpeed));
if (speed>maxSpeed) {
xSpeed *= maxSpeed/speed;
ySpeed *= maxSpeed/speed;
}
//
// move beetle based on calculations above
_y -= ySpeed;
_x += xSpeed;
//
//
// loop to opposite side of the masked area when the beetle travels off-screen
if (_y640) {
_y = 60;
}
if (_x560) {
_x = 40;
}

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-90;

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

i++;
timer = 30;
}
}
}

Kenney says: (reply)

Shooting in the direction the ship is facing requires understanding of trigonomy, so you should look that up first if you haven’t had that in school yet.

RaidsteeL says: (reply)

Thank you so much for this great tutorial!! I am new in flash and it helped me a lot!!!! You are awesome ;) !

steeljam says: (reply)

Great introduction to Flash and Actionscript. Thanks

Kevin says: (reply)

Hey, I’m a bit confused as to what I’m doing wrong. My ship moves just fine, my bullet linked just fine, but when I test the movie, the bullets don’t shoot. Yes, I did copy paste what you typed, but I also took the time to read and understand it all. When I play my movie, no errors pop up at all, and I can’t find the error in my coding. Any ideas what I’m doing wrong?

Kevin says: (reply)

Never mind, I figured it out. When I clicked on “Linkage” I needed to also check the box for “export in first frame.” You have the box checked in your tutorial, but you make no mention of actually doing so. For anyone else with bullets that don’t shoot, that might be your problem. You may want to make a mention of that in this Kenny, it will help noobs like myself. :D

Kevin says: (reply)

Hey, I found out the problem. When I clicked on “Linkage” I didn’t click on “Export in first frame.” You may want to make a mention of this Kenny, cause you only mention clicking “Export for Actionscript” Anyone else with issues like mine, double check your linkage. Hope this helps.

Vytautas says: (reply)

I agree with Kevin. ^
I have the same problem.

Werwar says: (reply)

Hi Kenney.
I have the same problem as Zasalamel.
the second bullet i added is a bit latthis

this is the code:

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.UP)){
_y -= 6;
}if(Key.isDown(Key.DOWN)){
_y += 6;
}

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

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

_root.attachMovie("laser2", "laser2"+i, _root.getNextHighestDepth());
_root["laser2"+i]._x = _x+65;
_root["laser2"+i]._y = _y-60;

_root["laser2"+i].onEnterFrame = function(){
this._y -= 20;
if(this._y < -30){
this.removeMovieClip();
}
}
}
}
i++;
timer = 15;
}}}

Werwar says: (reply)

is a bit late..misspell..:O

Spaminacan says: (reply)

Whenever I shoot my bullet, it disappears as soon as I shoot again. How do I stop this so I can get a faster rate of fire?

Kenney says: (reply)

You forgot to add 1 to the variable i, so it creates a new name for the next bullet. See my source.

Mary says: (reply)

I’m trying to make the bullets fire just a little bit faster. Is there any way of doing this? Thanks!

Kenney says: (reply)

Yeah, it’s very easy! Just change this line: this._y -= 10; and make the 10 something else, if you want to make it a little faster I suggest 15 or even 20.

Monteiro says: (reply)

Greetings, it might be stupid what i am asking next but is there a way you can see the axis on you’r stage?

Daniel says: (reply)

Hi,

This is a great tutorial but I’m wondering if there is a way to make the bullet to shoot out from the middle of the spaceship.
I would really appreciate it if you help me out.
Thanks!

    Kenney says: (reply)

    Well, if you did it right it should shoot from the center of the spaceship. Atleast horizontally, vertically it should be from the front.



Leave a Reply