Smooth Turning
An easy method to make an object aim at a location (in this case, the mouse cursor) but turn smoothly.
/**
* Copyright ChevyRay ( http://wonderfl.net/user/ChevyRay )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/pvmT
*/
package
{
import flash.geom.Point;
import flash.events.Event;
import flash.display.Shape;
import flash.display.Sprite;
public class SmoothTurning extends Sprite
{
public var leftTurret:Shape;
public var rightTurret:Shape;
public var targetNormal:Point = new Point(1, 0);
public var currentNormal:Point = new Point(1, 0);
public var lookEase:Number = 0.3;
public function SmoothTurning()
{
stage.frameRate = 60;
leftTurret = createTurret(100, 200);
rightTurret = createTurret(300, 200);
addEventListener(Event.ENTER_FRAME, update);
}
public function update(e:Event):void
{
//Left turret looks immediately
leftTurret.rotation = Math.atan2(mouseY - leftTurret.y, mouseX - leftTurret.x) * (180 / Math.PI);
//Right turret turns smoothly
targetNormal.x = mouseX - rightTurret.x;
targetNormal.y = mouseY - rightTurret.y;
targetNormal.normalize(1);
currentNormal.x += (targetNormal.x - currentNormal.x) * lookEase;
currentNormal.y += (targetNormal.y - currentNormal.y) * lookEase;
currentNormal.normalize(1);
rightTurret.rotation = Math.atan2(currentNormal.y, currentNormal.x) * (180 / Math.PI);
}
public function createTurret(x:int, y:int):Shape
{
var turret:Shape = new Shape();
turret.x = x;
turret.y = y;
turret.graphics.beginFill(0x000000);
turret.graphics.drawCircle(0, 0, 25);
turret.graphics.beginFill(0xFF0000);
turret.graphics.drawRect(-5, -5, 50, 10);
addChild(turret);
return turret;
}
}
}