Two Guys Arguing

mario math

Posted in java, mario, math by youngnh on 08.13.09

To calculate Mario’s velocity, with KEY_RIGHT pressed down continuously for n frames:

let a = 0.6 (1.2 if KEY_SPEED is held down as well)

at frame one, then, your velocity v_1 = a

frame 2: v_2 = a(.89) + a
frame 3: v_3 = (a(.89) + a).89 + a
frame 4: v_4 = ((a(.89) + a).89 + a).89 + a

which, if you multiply through, looks like this:

v_4 = a + a(.89) + a(.89)^2 + a(.89)^3

Which makes it a bit easier to generalize Mario’s velocity at any frame n:

v_n = \sum_{i=0}^{n-1}a(.89)^i

v_n = a * \sum_{i=0}^{n-1}(.89)^i

we know from paying attention in high school wikipedia that:

\sum_{i=0}^n x^i = \frac{1-x^{n+1}}{1-x}

however, our sequence only goes to n-1 frames. It’s missing the last term:

\left ( \sum_{i=0}^{n-1}x^i \right ) + x^n = \sum_{i=0}^n x^i = \frac{1-x^{n+1}}{1-x}

subtracting xn from both sides

\frac{1 - x^{n+1}}{1-x} - x^n = \frac{1-x^{n+1}}{1-x} - \frac{(1-x)}{(1-x)}x^n

= \frac{1-x^{n+1}-x^n+x^{n+1}}{1-x} = \frac{1-x^n}{1-x}

which we could have maybe figured out faster if we had remembered this identity:

\sum_{i=m}^n x^i = \frac{x^{n+1} - x^m}{x-1}

replacing the lower m with 0 and upper n with n-1 we get:

\sum_{i=0}^{n-1}x^i = \frac{x^{(n-1)+1}-x^0}{x-1}

=\frac{x^n-1}{x-1}

which multiplied by \left ( \frac{-1}{-1} \right ) is what we found earlier.

and so mario’s velocity after n frames of acceleration is:

v_n = a* \frac{1 - (.89)^n}{.11}

which can be calculated in constant time by this Java function:

public float velocityAfter(float accel, int nFrames) {
    return accel * ((1 - Math.pow(0.89, nFrames)) / 0.11);
}

Whew.

Thanks to Heath Borders and my co-blogger Ben for working this out on a whiteboard with me.

Tagged with: , , ,
Follow

Get every new post delivered to your Inbox.