# Managing animations for object state transitions

I'm looking for an optimized way to handle simple state transitions on my game objects. By "simple" I mean not more than 1-2 actions per object, and most algorithms are linear.

For example, I have an UI element that implements a switch (like a light switch) and it has two states - "up" (lights turned on) and "down" (lights turned off). Let's say I want to make it so that I can switch the switch from one state to another, and update its presentation in a smooth way using linear interpolation (move the foreground sprite up or down).

The question is if I should always check if the object should update its state (every frame), or should I add/remove this object from the update loop on demand, or is there any other (better) way of handling this situation?

Currently I have it implemented the following way: my object has a boolean variable called animated and in my onframe loop I have the following code:

if (this.animated)
/* calculate new positions for the sprite */
else
/* do nothing */


And it would appear to me that this kind of code is not very well optimized. How to handle this kind of things better?

I don't really understand, do you want to do animation or physics?

## Animation

Here is a simple, popular way of doing animation:

1. Define the starting state and end state for your object. This will vary depending on whether you want to move the object, rotate it, etc. An example would be to store the position of the object at the current state, and for the final/target/end state.
2. Then you subtract the coordinate values from each other
3. ... and multiply them by the magic variable f (in a lot of examples its referred to as f). f is a fraction between 0 and 1 that controls how far the animation is, or how what percentage of it has completed in other words.
4. Then you add the result from step 3 to the starting state.

Here is a crude psuedocode example for doing 2D translation animation:

State 1 [0,0]  State 2 [10,0]

f = (1 / anim_duration) * time_since_start_of_anim
current_x = state1_x + (f * (state2_x - state_x))
current_y = state1_y + (f * (state2_y - state_y))


The animation is finished if f = 1

Why this is a good approach:

• It is very easy to implement interpolation (like ease-in animation) by getting the value of f under some quadratic function
• It is very versatile and adaptable, making it easy to implement on a large number of objects

theory
https://en.wikipedia.org/wiki/Interpolation
Google has a nice page on how to make this approach look good
https://material.google.com/motion/material-motion.html#material-motion-how-does-material-move` (Sorry I don't have enough REP for more than two links)

## Physics

If you want to do physics, i.e. actual physics, then you have to use vectors. A simple(-ish) way of doing this is to calculate the acceleration for every delta t (time), add that to the object's velocity (a vector) and then update the object's position.