AS: Following/Shooting at Mouse
I'm not really in the mood for explaining the code, but this will hopefully be a good reference for the numerous requests for Actionscript to make something rotate to mouse and/or shoot at the mouse position.
SAMPLE
ROTATING TO MOUSE
For this part, you'll need one MC: your turret. Chuck it Stage centre, and give it the Instance Name gun
Add this code:
onClipEvent (mouseMove) {
Xd =_root._xmouse-_x; //Get _x distance from gun to mouse
Yd =_root._ymouse-_y; //Get _y distance from gun to mouse
radAngle = Math.atan2(Yd, Xd); //Use atan2 to calculate the angle from gun to mouse
_rotation = int((radAngle*360 / (2*Math.PI))+90); //Use PI to calculate and set gun rotation
updateAfterEvent();
}
CTRL+ENTER to test. Gun should now track the mouse.
MAKING BULLETS
For this, you'll need one more symbol, your bullet. Draw a rectangle pointing upwards, and convert to MC.
Since you'll probably want more than one bullet on-screen at a time, we'll use it as a base and make copies using duplicatedMovieClip(). Don't be scared.
Place an instance of your bullet on Stage, give it the Instance Name bullet, and add these actions to it:
onClipEvent(load){
spd=20; //bullet speed
_x=_root.gun._x; //Move to gun _x
_y=_root.gun._y; //Move to gun _y
_rotation= _root.gun._rotation; //Point in same direction as gun
}
onClipEvent(enterFrame){
if(_name == "bullet"){
_x = -1000; //Move the original bullet MC offstage
}else{
//Run this movement code on all dupes
if (_rotation>180) {
_y += (spd*Math.cos( Math.PI/180*_rotation));
_x -= (spd*Math.sin( Math.PI/180*_rotation));
} else {
_y -= (spd*Math.cos (Math.PI/180*_rotation));
_x += (spd*Math.sin( Math.PI/180*_rotation));
}
//if(hitTest(_root.enemy)){ blahh; } Not going to address this here, check AS: Main for hitTest threads.
}
if(_x>Stage.width || _x<0 || _y<0 || _y>Stage.height){
//If off-stage, delete the dupe to save CPU
this.removeMovieClip();
}
}
FIRING AT MOUSE
Now all we need is the 'trigger' code that will produce copies of the bullet. Once created, the dupes will run their code which will send them off in the direction of the mouse.
Add this code to the first frame, main timeline:
var bc=1000; //bulletcount
_root.onMouseDown=function(){
bc++;
if(bc>1100){ bc=1000; } //Reset bulletcount
duplicateMovieClip("bullet", "b"+bc, bc); //Create dupe bullet
}
That's it.