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 */ 
    /* 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?


1 Answer 1


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 function
  • It is very versatile and adaptable, making it easy to implement on a large number of objects

You must log in to answer this question.

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