ActionScript: Throw bullets to mouse direction

[:en]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.

[swf:/wp-content/uploads/2010/12/www.benoitfreslon.com_Throw_bullets_to_mouse_direction.swf 640 400]

import flash.display.MovieClip;
import flash.geom.Point;
import flash.events.MouseEvent;

// Code by Benoit Freslon.
// Tutorials, Flash games:
// https://www.benoitfreslon.com

// This object will always look at the mouse cursor
myTank.addEventListener(Event.ENTER_FRAME, tankEnterFrame);
// This function will be launched every frame (25 times by seconds);
function tankEnterFrame(pEvt) {
	// pEvt.currentTarget: myTank
	var mc = pEvt.currentTarget;
	// Get the radian angle between the tank and the cursor
	// You can also replace mouseX and mouseY by another coordinates
	var angleRadian = Math.atan2(mouseY - mc.y,mouseX - mc.x);
	// Convert the radian angle in dedree angle
	var angleDegree = angleRadian * 180 / Math.PI;
	// Set the orientation
	mc.rotation = angleDegree;
	// Display angle of rotation in degree
	txtAngle.text = Math.round(angleDegree) + "°";
}

// Add a mouse down event on stage
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);

function mouseDown(pEvent) {
	// Create a new bullet
	var b = new Bullet();
	// Set his position to the tank position
	b.x = myTank.x;
	b.y = myTank.y;
	// Save the randian angle between the mouse and the tank
	// This angle will set the direction of the bullet
	b.angleRadian = Math.atan2(mouseY - myTank.y,mouseX -myTank.x);
	// Add an enter frame event on each bullet
	b.addEventListener(Event.ENTER_FRAME, bulletEnterFrame);
	// Add this display object on the display list
	addChild(b);
}

// Velocity of each bullet
var speed = 8;

function bulletEnterFrame(pEvent) {
	// Get the current object (Bullet)
	var b = pEvent.currentTarget;
	// Move this bullet on each frames
	// On X axis use the cosinus angle
	b.x +=  Math.cos(b.angleRadian) * speed;
	// On Y axis use the sinus angle
	b.y +=  Math.sin(b.angleRadian) * speed;
	// Orient the bullet to the direction
	b.rotation = b.angleRadian * 180 / Math.PI;
	// You have to remove each created bullet
	// So after every moves you must check bullet position
	// If the bullet is out of the screen
	if (b.x < 0 || b.x > 400 || b.y < 0 || b.y > 400) {
		// Remove it from the display list
		removeChild(b);
		// /!\ AND REOMOVE HIS EVENT LISTER
		b.removeEventListener(Event.ENTER_FRAME, bulletEnterFrame);
	}
}

Download source: www.benoitfreslon.com_Throw_bullets_to_mouse_direction.zip[:fr]Après avoir calculé l’angle entre 2 objets vous pouvez maintenant utiliser cet angle pour par exemple lancer des projectiles en direction d’un objet avec un peu de trigonométrie.

Comment ?

  1. Calculer l’angle (en radian) entre les 2 objets graphiques avec la méthode Math.atan2.
  2. Au clic afficher un nouveau projectile à la position du tank et ajouter un évènement enter frame sur ce projectile.
  3. Sauvegarder l’angle entre le tank et le curseur dans le projectile.
  4. Utiliser l’angle pendant l’évènement enter frame pour calculer la vitesse en x et en y avec le cosinus et le sinus.

[swf:/wp-content/uploads/2010/12/www.benoitfreslon.com_Throw_bullets_to_mouse_direction.swf 640 400]

import flash.display.MovieClip;
import flash.geom.Point;
import flash.events.MouseEvent;
// Code by Benoit Freslon.
// Tutorials, Flash games:
// https://www.benoitfreslon.com
// Cet objet regardera constamment la souris.
myTank.addEventListener(Event.ENTER_FRAME, tankEnterFrame);
// Cette fonction est lancée 25 fois par seconde.;
function tankEnterFrame(pEvt) {
	// pEvt.currentTarget: myTank
	var mc = pEvt.currentTarget;
	// Calculer l'angle en radians entre la souris et l'objet
	var angleRadian = Math.atan2(mouseY - mc.y,mouseX - mc.x);
	// Convertir l'angle radians en degrés.
	var angleDegree = angleRadian * 180 / Math.PI;
	// Orienter l'objet.
	mc.rotation = angleDegree;
	// Afficher l'angle en degrés sur l'interface.
	txtAngle.text = Math.round(angleDegree) + "°";
}
// Ajouter un évènement souris qui se déclenchera au clic.
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
function mouseDown(pEvent) {
	// Ajouter un nouveau projectile
	var b = new Bullet();
	// Placer le projectile aux coordonnées du tank.
	b.x = myTank.x;
	b.y = myTank.y;
	// Enregistrer l'angle dans le projectile.
	// Cet angle orientera le projectile
	b.angleRadian = Math.atan2(mouseY - myTank.y,mouseX -myTank.x);
	// Ajouter un écouteur d’évènement ENTER_FRAME)
	b.addEventListener(Event.ENTER_FRAME, bulletEnterFrame);
	// Afficher le projectile sur la scène
	addChild(b);
}
// Vitesse du projectile
var speed = 8;
function bulletEnterFrame(pEvent) {
	// Enregistrer l'objet cible dans une variable
	var b = pEvent.currentTarget;
	// Bouger l'objet entre chaque frame
	// Sur l'axe X utiliser le cosinus de l'angle
	b.x +=  Math.cos(b.angleRadian) * speed;
	// Sur l'axe Y utiliser le sinus de l'angle
	b.y +=  Math.sin(b.angleRadian) * speed;
	// Orienter l'objet en fonction de l'angle en degrés.
	b.rotation = b.angleRadian * 180 / Math.PI;
	// Mais il faut supprimer les projectiles lorsqu'ils se retrouvent dehors
	// Si le projectile est hors de l'écran
	if (b.x < 0 || b.x > 400 || b.y < 0 || b.y > 400) {
		// Supprimer le projectile de l'affichage
		removeChild(b);
		// /!\ ET RETIRER SON ECOUTEUR ENTER_FRAME
		b.removeEventListener(Event.ENTER_FRAME, bulletEnterFrame);
	}
}

Télécharger les sources : www.benoitfreslon.com_Throw_bullets_to_mouse_direction.zip[:]

Author: Benoit Freslon