kekona
kekona

Reputation: 85

Ease rotation and position of MovieClip to mouse, math help

Essentially what I'm trying to do is nearly the same as this: http://www.senocular.com/flash/source/?id=0.16

However I'd like to ease/tween the movieclip position and rotation to the mouse position.

The main issue I see is trying to get the current movieclip rotation and the target rotation, then tween it cockwise or counterclockwise from current to target. The way a movieclips rotation uses positive and negative numbers throws it off. If you just want to lock the mc rotation to the mouse rotation its fine, but once you try to tween it you run into difficulties.

So the end effect would be like if you were to draw imaginary clockwise circles around the object, it should just keep rotating clockwise towards the mouse. Then if you started going counter clockwise it should just keep easing counter clockwise to the mouse.

Thanks for any help.

Upvotes: 1

Views: 2255

Answers (1)

Adam Harte
Adam Harte

Reputation: 10510

So there are two parts. One, you want to find the shortest angle between two angles. Two, you need to ease between the angles and position.

Finding shortest angle.

angleDelta will be the shortest rotation angle between your two angles.

var angleDiff:Number = angleTo - currentAngle;
var angleDelta:Number = Math.atan2(Math.sin(angleDiff), Math.cos(angleDiff));
angleDelta *= (180/Math.PI); // Change angle from Radians to Degrees.

Ease between values

I usually use a simple equation in some kind of loop (usually enterFrame) to ease between simple values.

addEventListener(Event.ENTER_FRAME, enterFrameHandler);
private function enterFrameHandler(e:Event):void 
{
    rotation += (targetRotation - currentRotation) * 0.2;
    x += (targetX - currentX) * 0.4;
    y += (targetY - currentY) * 0.4;
}

EDIT*

This should work for you.

const TO_DEGREES:Number = 180 / Math.PI;
const TO_RADIANS:Number = Math.PI / 180;

addEventListener(Event.ENTER_FRAME, enterFrameHandler);

function enterFrameHandler(e:Event):void
{
    var angleTo:Number = Math.atan2(stage.mouseY - y, stage.mouseX - x) * TO_DEGREES;
    if (angleTo > rotation+180) angleTo -= 360;
    if (angleTo < rotation-180) angleTo += 360;

    rotation += (angleTo - rotation) * 0.2;
    x += (stage.mouseX - x) * 0.2;
    y += (stage.mouseY - y) * 0.2;
}

Upvotes: 2

Related Questions