I was recently asked how to have objects that animate themselves (change frames) in a stable way that isn't dependent on the FPS or lag of the device. There are many ways to do this but I have a simple one which uses the difference between the last tick and the current tick to count down. My example is in Java and is suitable for most games. The first step is to use a main loop which gives the updates that info. The best way to do this is to give every thing that is updating the exact same time information and have them all use that.
Use a basic World class that holds the state of everything, including the tick time information.
Find any rogue calls to System.currentTimeMillis() and change them to use world.curTickMs
This update() method is what I call from run() in a loop in the Thread.
After that, the animations can be done in one of the update() calls and they can do something like this:
public void updateAnimation(World world) {
delayRemainder -= world.tickDelta;
if (delayRemainder < 0) {
currentAnimationFrame++;
delayRemainder = FRAME_DELAY;
if (currentAnimationFrame > FRAMES) {
currentAnimationFrame = 0;
}
}
}
public void draw(Canvas canvas) {
//draw bitmap for currentAnimationFrame
}
There are other ways to do this but this method works well because it uses world time and can pause the animation, provided that the main loop resets the lastTick and Tick Delta on pause.
1 Comment
Post a comment here or discuss this and other topics in the forumsThanks SOO much! I love it
Thanks SOO much! I love it
Post new comment