- Home
- Tutorials
- Flash
- Intermediate
- Shooting Bullets
Shooting Bullets

Function fire();
Insert or type out the following
function fire(){
if(reloaded){
x=_root.getNextHighestDepth();
var bullet:MovieClip=_root.attachMovie("bullet", "bullet"+x, x);
bullet._x=turret._x;
bullet._y=turret._y;
randomNum=random(bulletOffset)-bulletOffset/2;
bullet._rotation=turret._rotation+randomNum;
bullet.xSpeed=Math.cos(Math.PI/180 * bullet._rotation)*bulletSpeed;
bullet.ySpeed=Math.sin(Math.PI/180 * bullet._rotation)*bulletSpeed;
bullet.life=0;
bullet.onEnterFrame=function(){
this._x+=this.xSpeed;
this._y+=this.ySpeed;
this.life++;
if(this.life>totalLife){
this.removeMovieClip();
this.unloadMovie();
};
};
reload();
};
};
function reload(){
reloaded=false;
timer=setInterval(this, "Reloaded", reloadSpeed);
}
function Reloaded(){
clearInterval(timer);
reloaded=true
}
Reloading:
Functions are powerful ways to reuse blocks of code over and over again, in this example 'function fire()' can only be executed if reloaded=true. Since we have declared reloaded as a variable already and set it to true it will fire a round from the turret every frame. But to make this more realistic we want to control how fast it creates bullets (instead of one every frame).
So before we end the if statement if(reloaded) we execute the function 'reload' which sets reloaded to false and creates a timer based on the reloadSpeed var. When the timer finished it executes the "Reloaded" function, which sets reloaded to true and clears the timer for endless uses, without clearInterval the timer would keep counting so it is already beyond the reloadSpeed and cannot make reloaded true.
Now we know how it reloads and what a function is, lets explain the rest of it. Next Page!

