0
\$\begingroup\$

I have a question about my code. I wrote a basic GameLoop for an Android Game and while testing it I realized the deltaTime is always 0.

The code looks like this:

@Override
 public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        lastTime = System.currentTimeMillis();
    }

@Override
    public void onDrawFrame(GL10 gl) {
        float currTime = System.currentTimeMillis();
        float deltaTime = currTime - lastTime;
        float msPerFrame = 1000.0f/ 60.0f;

        if(deltaTime < msPerFrame){
            try {
                Thread.sleep((long)(msPerFrame-deltaTime));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        update(deltaTime, gl);
        lastTime = currTime;

    }

    public void update(float deltaTime, GL10 gl){
           //doStuff
    }

lastTime and currTime are always the same and the deltaTime is 0. I don't know if this is right or the code is just wrong but I think the deltaTime shouldn't be 0...

I test the app with Android Studios Emulator.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ don't sleep in event handlers, just draw (without update) and return and schedule the next draw frame \$\endgroup\$ Mar 29, 2016 at 14:24
  • \$\begingroup\$ @ratchetfreak ah okay thank you, didn't know that this is the better option. :) \$\endgroup\$
    – Godlike
    Mar 30, 2016 at 6:13

1 Answer 1

1
\$\begingroup\$

All those time functions work with the datatype long. Try changing float to long to avoid potential rounding errors.

currentTimeMillis() might not be accurate enough. Try System.nanoTime() instead: https://stackoverflow.com/questions/351565/system-currenttimemillis-vs-system-nanotime

\$\endgroup\$
1
  • \$\begingroup\$ Thank you, you are right. I changed float to long and everything is working fine. \$\endgroup\$
    – Godlike
    Mar 29, 2016 at 14:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .