jgranick/spritesheet — pull request #4 by supremefist (2013-11-03 14:54:24+00:00)
Title: Fixed rounding error with frame index selection.

Hi Joshua,

First off, thanks for your great work with the spritesheet lib you made for haxe! I am using it to great effect!

I found a small issue with frame index selection. Let me demonstrate my problem by means of an example:

Let's assume you have 3 frames [A, B, C] in an animation that has a duration of 1 second.

You select your currentFrameIndex with the line:
currentFrameIndex = Math.round (ratio * (currentBehavior.frames.length - 1));

Let's go through a typical cycle and which frames would be selected.

After 0 ms, the currentFrameIndex will be 0.1 * (3 - 1) = Math.round(0.2) = 0
After 100 ms, the currentFrameIndex will be 0.1 * (3 - 1) = Math.round(0.2) = 0
After 200 ms, the currentFrameIndex will be 0.2 * (3 - 1) = Math.round(0.4) = 0
After 300 ms, the currentFrameIndex will be 0.3 * (3 - 1) = Math.round(0.6) = 1
After 400 ms, the currentFrameIndex will be 0.4 * (3 - 1) = Math.round(0.8) = 1
After 500 ms, the currentFrameIndex will be 0.5 * (3 - 1) = Math.round(1.0) = 1
After 600 ms, the currentFrameIndex will be 0.6 * (3 - 1) = Math.round(1.2) = 1
After 700 ms, the currentFrameIndex will be 0.7 * (3 - 1) = Math.round(1.4) = 1
After 800 ms, the currentFrameIndex will be 0.8 * (3 - 1) = Math.round(1.6) = 2
After 900 ms, the currentFrameIndex will be 0.9 * (3 - 1) = Math.round(1.8) = 2
After 1000 ms, the currentFrameIndex will be 1.0 * (3 - 1) = Math.round(2.0) = 2

From these frame indices, you can see that the middle frame gets a much longer display time! In fact, it is double the time of the other frames, which results in an uneven animation. This is due to the rounding spending a long time (second and third quarters of the second) rounding to one.

I have made a change to make the animation work in terms of the duration in ms of a frame and the amount of time we have been busy with the animation, which results in a fair time distribution between frames.

Please consider the changes I proposed! I have broken up the code into simple steps, but the code doesn't need to be as long winded and can be shortened.

Thanks for your time,
Riaan