I'm working in JavaScript with HTML5 and the canvas. I have an object which is rotating at a certain speed, and I need the object's rotation to slow down gradually and the front of the object to stop at a specified angle. (I'm using radians, not degrees.) I have a variable to keep track of the angle which the object is facing, as it rotates.

How would I go about getting the object to come to rest, facing the direction I want it to?


2 Answers 2


maybe a good way of seeing the problem is to ask : - can i do another cycle ?

count the number of cycle, and see if this is the begining of a cycle:

var beginingNewCycle=false;
numCycle = Math.floor ( (angle - endAngle ) / 6.28318531 ;
if (old_numCycle != numCycle) beginingNewCycle=true; 

( when the rotation starts,
you should : 1) reset angle with angle=angle % 6,28318531 ;
and 2) set old_numCycle to -1

So when you have a new cycle, ask yourself if this will be the last, for example if speed < threshold. Then you do the last turn controlling the speed fade-out to zero.

for instance for the fade out, you can use :

 var rotSpeedAtenuation =  1 -   ( (angle-EndAngle) % 6.28318531 ) / 6.28318531 ;

which is a number going from 1 to 0 linearly as angle gets nearer from goal. multiply the speed by this number, but keep a minimum speed not to freeze the object before arrival.

But linear might be hugly, maybe you want to 'shape' the atenuation, like for
instance with :

  var sqM1 = function (x) { return 1 - x*x ;}

and you use sqM1(rotSpeedAtenuation) to multiply to current speed.


Visualise a graph of rotation versus time that gradually drops to zero and notice there is an infinite number of ways of drawing such a graph. First, you'll have to specify how you want the angular velocity to decrease. Formulate a function ω(t) that equals the starting angular velocity (s) at t=0 and drops to zero eventually (t=T). Tune the variables to match the following criterium: ω(t) integrated over t from 0 to T equals the rotation yet to be covered. An example:

I want my angular velocity to decrease in a linear fashion, i.e.: ω(t) = s + a t. To find T, we solve: s + a T = 0, ergo: T = -s/a. Integrating yields that the angle covered in this gradually decelerated rotation equals -½ s² / a. Solving for a gives us the desired angular velocity at every timestep, which we can numerically integrate as we go to find the current angle, or do this in advance to obtain a function angle of time which we can use directly.

  • \$\begingroup\$ This is a great answer :) \$\endgroup\$
    – lapin
    Dec 14, 2012 at 0:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .