# sine animation with varying speed

This topic is 4138 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

hello, i am animating something based on a sine curve: animatedvalue = sin(passedTime() * speed); now i want to smoothly change the animation speed. if i just modify the speed variable, the animation directly jumps to a new position since, depending on the time, the sine could be somewhere completely else. how can i change the speed of a sine animation seamlessly?

##### Share on other sites
I do not know if this is applicable but I would have tried to do it like this.

long animPos = 0;atUpdate(long timeSinceLastUpdate){  animPos += timeSinceLastUpdate * speed;  animatedvalue = sin(animPos);}

##### Share on other sites
Well, if you want to instantly change speed, but keep everything "in phase", then you'll need an additional variable in your sin() function.
animatedvalue = sin(passedTime() * speed + offset);
When you first initialize your values, offset can be 0. However, if you ever need to change speed, you can recalculate offset so that everything matches and you don't get the ugly discontinuity. (Note that I'm assuming C++, and assuming that your datatypes are all double. Change as necessary.)
const double PI_TIMES_TWO = 6.283185307179586476925286766559;double speed = 1.0;double offset = 0.0;double CalculateAnimatedValue(){  return sin(passedTime() * speed + offset);}void ChangeSpeed(double newSpeed){  double time = passedTime();  double currentTime = time * speed + offset;  double unadjustedNewTime = time * newSpeed;  double currentOffset = fmod(currentTime, PI_TIMES_TWO);  double unadjustedNewOffset = fmod(unadjustedNewTime, PI_TIMES_TWO);    speed = newSpeed;  offset = currentOffset - unadjustedNewOffset;}
There may be a better way to do this (and this may actually be incorrect code, I didn't test it), but I think it should work. Basically, I calculate the current time of the animation, and the new time of the animation if I used the new speed and no offset value at all. Then I use fmod to calculate where in a single cycle of a sine wave the animation is currently in, and where it would be if I switched to the new speed. I then subtract the latter from the former to get the new offset, which should (hopefully) be exactly what is needed to match up the old sine wave with the new sine wave.

thanks a lot!

that works!

• 10
• 17
• 9
• 14
• 41