Search code examples
androidaccelerometer

Android: Achieving smooth roll of ball using accelerometer


I have developed a maze game for Android where you control the ball by tilting the phone.

So I use the accelerometer and integrate the x and y accelerometer values and then move the ball a step in that direction.

I have a problem though, I cannot achieve a very smooth roll. When the ball picks up speed it is to obvious that it jumps in big discrete steps. I have seen other apps like this where the ball rolls fast but smoothly.

So I might have to change my strategy, use some sort of time solution instead. Now the faster the speed the bigger the step I move. Instead maybe I should have a timer that moves the ball 1 pixel every ms if speed is high or only every 10th ms if the speed is low or something along those lines. Or how do people achieve a smoother roll?

Also: Would you use OpenGL for this?


Solution

  • What you're really doing here is integrating coupled differential equations. Don't worry if you haven't taken enough calculus or physics to know what that means.

    People who integrate coupled differential equations for a living have evolved many algorithms to do so efficiently.

    You really have four equations here: acceleration in x- and y-directions and velocity in x- and y-directions:

    dvx/dt = ax
    dvy/dt = ax
    dsx/dt = vx
    dxy/dt = vy
    

    (sx, sy) give the position of the ball at a given time. You'll need initial conditions for (sx, sy) and (vx, vy).

    It sounds like you've chosen the simplest way to integration ODEs: Euler explicit integration. You calculate the values at the end of a step from the values at the beginning plus the rate of change times the time step:

    (vx, vy)_1 = (vx, vy)_0 + (ax, ay)_0 * dt
    (sx, sy)_1 = (sx, sy)_0 + (vx, vy)_0 * dt
    

    It's easy to program, but it tends to suffer from stability problems under certain conditions if your time step is too large.

    You can shrink your time step, which will force you to perform the calculations many more times, or switch to another integration scheme. Search for implicit integration, Runge-Kutta, etc.

    Integration and rendering are separate problems.