Slowly Change One Angle To Another
Solution 1:
Well, here's a working fiddle for your solution -> Fiddle Link <-.
Mind you, I've changed some of the variables names, and added comments.
Regarding some of issues with your code:
The negative angle was because you called atan2 with current-target
, instead of target-current
. You should give the atan2 the difference between the flyTo and flyPos, since that will be the equivalent of looking at the target from where you are (which is the way atan2 works). So:
var my_angle = Math.atan2(flyPos[1]-flyTo[1],
flyPos[0]-flyTo[0]) -Math.PI;
should have been:
var my_angle = Math.atan2(flyTo[1]-flyPos[1],
flyTo[0]-flyPos[0]);
And then you shouldn't have worried about the -PI
.
Speed should be always positive, since it's a scalar, and we have the direction (also, negative speed = positive speed in negative direction).
I've added decelerate
and accelerate
methods, mainly to avoid the annoying "buzz" when the text tries to reach the target, and keeps moving back and forth between tiny locations. Now it'll decelerate when it get's closer, and accelerate if you move away.
A small thing to note: according to MDN you should call your setInterval
like this:
setInterval( letter.flyAway, refreshEvery );
instead of with the self executing method (and it's much easier on the eyes as well).
To get your nice round turning, what we want to do is look at the current direction, and slowly change towards the target direction.
A possible bug exists in the following naive implementation (where dPhi
stands for delta phi, a small angle):
if ( Math.abs(angle_to_target - direction) > dPhi )
if (angle_to_target > direction)
direction += dPhi;
else
direction -= dPhi;
else
direction = angle_to_target;
If direction is for example 179 deg, and the target is 181 deg, instead of closing the 2 degree gap, it'll go through the 358 degree AROUND the other side. The reason is the way atan2
deals with the angle, returning values between -PI
and PI
. The solution is to add 2*PI
in a couple of cases:
if (direction - Math.PI > angle_to_target )
angle_to_target += 2*Math.PI;
if (angle_to_target - Math.PI > direction )
direction += 2*Math.PI;
There you go, working fiddle with start
and stop
buttons will show you the results.
You might want to add the random speed
/ angle
to that solution, but that shouldn't be hard now :)
Post a Comment for "Slowly Change One Angle To Another"