In the last session i briefly talked about trig, now lets put it into action.
Ok, heres all the code you need to make a turret rotate.
stage.frameRate = 30;
var angle:Number = 0;
var radiansToDegrees:Number = 180/Math.PI;
var turret:MovieClip = new MovieClip();
turret.graphics.beginFill(0xFFFFFF);
turret.graphics.lineStyle(2, 0xFFFFFF);
turret.graphics.drawRect(-10, 0, 20, 40);
turret.graphics.endFill();
turret.graphics.beginFill(0xFFFFFF);
turret.graphics.drawCircle(0,0,20);
turret.graphics.endFill();
turret.x = 275;
turret.y = 200;
addChild(turret);
turret.addEventListener(Event.ENTER_FRAME, rotateTurret);
function rotateTurret(event:Event):void {
angle = Math.atan2(mouseY-turret.y, mouseX-turret.x);
angle *= radiansToDegrees;
turret.rotation = angle – 90;
}
line 1: Setting the frames per second of the movie, anything above 30 makes it smooth
line 2: Creating a new number variable called angle, no guesses for what it will be storing.
line 3: As we are going to get an angle in radians and flash does rotation in degrees we need to convert those radians to degrees. This simple sum does that and i have made a variable of it at the start to optimize performance.
lines 4-14: These have already been explained earlier.
line 15: Adding a listener to “turret” to trigger once a frame, hence Event.ENTER_FRAME, the function “rotateTurret”;
line 16: The function “rotateTurret” is being set up, it is a general function so it has a basic event:Event description.
line 17: Setting the angle variable to get our angle in radians as described earlier.
line 18: Converting the angle to degrees
line 19: Rotating the turret moviCllip by the new angle number with 90 degrees taken off to make it point towards the mouse.
It should look like this.
Ok you should be able to create dynamically rotating objects. My next tutorial will show you how to shoot.


