Skip to main content
December 24, 2014
Question

Moving a movieclip in a certain direction

  • December 24, 2014
  • 1 reply
  • 204 views

Hi!

So, i got this movie clip (say a military tank), and i have attached to it a missile by script. When the tank moves, the missile moves with it, and when the tank rotates, the missile rotates with it. Now what i want it, when i hit the space button, to shoot the missile in the direction it is pointed to. How can i do this, please? Kindly advice how to do it please.

Here's a video clip of my tank and missle: http://youtu.be/ksA8BM-z4kU

Thanks for any response.

KasunL

This topic has been closed for replies.

1 reply

kglad
Community Expert
Community Expert
December 24, 2014

if you chose your transform points wisely, you can use the tanks rotation property to direct your missile.  but don't attach to the missile to the tank.  that will be problematic for more than 1 reason.

so you would usually look something like the following in a loop (eg, enterframe) and you may need to adjust the tanks rotation if its default rotation of 0 fails to point towards the position x axis.:

missile.x+=speed*Math.cos(Math.PI*tank.rotation/180);

missile.y+=speed*Math.sin(Math.PI*tank.rotation/180);

eg,

var m:Missile;

var speed:int=whaTEVER;

var tankW:Number = tank.width;

function bF(e:KeyboarEvent):void{

m=new Missile();

this.addChild(m);

m.rotation=tank.rotation;

m.x = tank.x+tankW/2*Math.cos(tank.rotation*Math.PI/180);

m.y = tank.y+tankW/2*Math.sin(tank.rotation*Math.PI/180);

m.addEventListener(Event.ENTER_FRAME,enterframeF);

}

function enterframeF(e:Event):void{

e.currentTarget.x+=speed*Math.cos(Math.PI*e.currentTarget.rotation/180);

e.currentTarget.y+=speed*Math.sin(Math.PI*e.currentTarget.rotation/180);

if(e.currentTarget.x>stage.stageWidth||e.currentTarget.y>stage.stageHeight||e.currentTarget.x<0||e.currentTarget.y<0){

this.removeChild(MovieClip(e.currentTarget));

e.currentTarget.removeEventListener(Event.ENTER_FRAME,enterframeF);

}

}