ActionScript: Throw bullets to mouse direction

After calculating the angle of 2 graphic objects, you can also use this angle to throw a bullet to the object direction with the trigonometry.

How ?

  1. Calculating the angle (in radian) between 2 graphics objects with the Math.atan2 method (cf. Orient object to the mouse cursor).
  2. On click, display a bullet to the “tank” position and add an “enter frame” event on this bullet.
  3. And save the angle between the tank and the mouse cursor on the new  bullet.
  4. Use this angle on the “enter frame” event to calculate the x and y speed with the cosinus and the sinus.

Download source: www.benoitfreslon.com_Throw_bullets_to_mouse_direction.zip

11 thoughts on “ActionScript: Throw bullets to mouse direction

  1. Any chance you could post a .fla file for your sample of the firing tank? Would be pretty useful to see the library clips you have created etc.

    Would be greatly appreciated. Thanks.

  2. Great piece of code. I am just pulling my hairs over something that seems simple: How would you go about randomizing one of the components so it appears that the cannon shoots with some inaccuracy? I randomized the position of the mouse as ti simulate inaccurate clicks. The problem arises when you click near the tank, then the bullet moves in any direction around it.

  3. I am nearly going bald but I managed to solve it with a bit of a dirty trick: convert the angle to degrees, add random integer to that, then convert back to radians. Works like magic.

  4. Prolific as3 code I have ever found. All blog member do’nt want to give real necessary code. Please could you give me as3 code that is curve showing the angular value of an angle and if right angle it will draw appropriate line rather curve.

  5. first my apologies by the my english.
    i’m trying create a game of aircraft, but the code that i created don’t worked as i would.

    below there’s a piece of code…

    private function criaPersonagem()
    {
    player = new Player(stage,10,10);
    player.x = stage.stageWidth / 2;
    player.y = stage.stageHeight – player.height;

    addChild(player);
    player.addEventListener(Event.ENTER_FRAME , rotacionar);
    stage.addEventListener(MouseEvent.CLICK , atirou)

    }

    private function atirou(e:MouseEvent):void
    {
    var tiro:Tiro = new Tiro(player,radians,angulo);
    tiro.x = player.x;
    tiro.y = player.y;
    addChild(tiro);
    }

    private function rotacionar(e:Event):void
    {

    var mc = MovieClip(e.currentTarget);
    radians = Math.atan2(stage.mouseY – mc.y,stage.mouseX – mc.x);
    angulo = radians * 180 / Math.PI;
    rad_txt.text = radians.toString();
    angulo_txt.text = angulo.toString();
    cos_txt.text = Math.cos(radians).toString();
    seno_txt.text = Math.sin(radians).toString();
    mc.rotation = angulo;

    }

    but this code no work correctly as wished.

Leave a Comment