ActionScript: Orient an object to the mouse cursor with Flash

[:en]How to orient an objet to an other ? Just put those lines and change the instance name myTank.

[swf:/wp-content/uploads/2010/01/Orienter_un_objet_par_rapport_a_un_autre-1.swf 300 300]

Download the source code here: [www.thisisgameplay.com]_Orient_object_to_mouse_cursor.fla

// 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
	var angleDegree = angleRadian * 180 / Math.PI;
	// Set the orientation
	mc.rotation = angleDegree;
	// Display angle of rotation in degree
	txtAngle.text = Math.round(angleDegree) + "°";
}

[:fr]Voici comment orienter un objet graphique de type MovieClip en Flash vers le curseur de la souris.
Copier/Coller le script dans Flash et remplacer le nom d’instance myTank par le vôtre.

[swf:/wp-content/uploads/2010/01/Orienter_un_objet_par_rapport_a_un_autre-1.swf 300 300]

// Cet objet regardera tout le temps le curseur
myTank.addEventListener(Event.ENTER_FRAME, tankEnterFrame);
// Cette fonction est lancée à chaque frame 25 fois par seconde.;
function tankEnterFrame(pEvt) {
	// pEvt.currentTarget = myTank
	var mc = pEvt.currentTarget;
	// Calculer l'angle en radians entre les 2 objets
	// On peut aussi remplacer les coordonnées de la souris par d'autres.
	var angleRadian=Math.atan2(mouseY-mc.y,mouseX-mc.x);
	// Convertir l'angle radian en degrés.
	var angleDegree = angleRadian * 180 / Math.PI;
	// Orienter le symbole mc
	mc.rotation = angleDegree;
	// Afficher l'angle en degrés sur l'interface
	txtAngle.text = Math.round(angleDegree) + "°";
}

Télécharger les sources: [www.thisisgameplay.com]_Orient_object_to_mouse_cursor.fla[:]

Author: Benoit Freslon