2
\$\begingroup\$

I have fixed timestep code in my main thread, it looks like this:

float oldTimeSinceStart = 0;
float accumulatedTime = 0;
float maxDeltaTime = 0.1f; // 10 FPS
float fixedTime = 0.016f; // 60 FPS

while(running)
{
    float timeSinceStart = System.nanoTime();
    float deltaTime = (timeSinceStart - oldTimeSinceStart) / 1000000000;
    oldTimeSinceStart = timeSinceStart;

    deltaTime = Math.min(deltaTime, maxDeltaTime);

    accumulatedTime += deltaTime;

    while (accumulatedTime >= fixedTime)
    {
        accumulatedTime -= fixedTime;

        gamePanel.update();
    }

    gamePanel.draw(canvas);
}

I have objects on scene, which positions are updated as

position += speed; 

And speed is calculated on app start as

speed = (screenWidth / 2) * fixedTime;

These codes should work well to get same objects speeds on all devices and also smooth visual. Speed works quite well, but visual appereance is bad. I'm getting periodical "lags" about each half second on my old Galaxy Ace and also on S III Mini. So it's like running smoothly - lag - running smoothly - lag...

Any ideas what could cause these lags?

\$\endgroup\$
8
  • 1
    \$\begingroup\$ My bet is on GC. Android is infamous for scheduling lenghty gc in the worst times - does System.gc(); after drawing help? \$\endgroup\$
    – wondra
    Dec 13, 2015 at 13:03
  • \$\begingroup\$ With that it does running periodical without the lag I've described, but with smaller lags (to compare it, it looks like when you running game on 10FPS so you see its lagging, but the game runs still on 10FPS - no drops). So, it's constant laggy movement. \$\endgroup\$
    – johnyX
    Dec 13, 2015 at 13:23
  • 1
    \$\begingroup\$ Good, that is an improvement. Now try to create less garbage. Also, what(class of gamePanel) are you drawing onto? I know there are better(and worse) suited options. \$\endgroup\$
    – wondra
    Dec 13, 2015 at 13:31
  • \$\begingroup\$ So you mean I have to clear up and simplify code as much as possible right? Second question: sorry, I don't know what do you exactly mean. I'm calling draw(Canvas canvas) in gamepanel, and drawing physics and objects from there (doing player.draw(), walls.draw()...). \$\endgroup\$
    – johnyX
    Dec 13, 2015 at 13:44
  • 1
    \$\begingroup\$ Let us continue this discussion in chat. \$\endgroup\$
    – wondra
    Dec 13, 2015 at 14:45

0

You must log in to answer this question.

Browse other questions tagged .