Java2D time-based movement

Question:

I'm trying to move an object using Java2D but I'm having some problems, I have the following method:

public void logics() throws Exception{
    before = System.nanoTime();
    loop.logics(diff);
    after = System.nanoTime();
    diff = after - before;
}

Inside the loop.logics(long delta) I have the following code:

double ddelta = delta/1000000000.0;
x += speed*ddelta;// delta é a variação em segundos
System.out.println(x);

x and speed start at 100, however the result I see on the output is:

...
101.01591999999998
101.02638559999998
101.03550849999998
101.04340709999998
101.06836669999998
101.13834839999998
101.14830059999998
101.15935859999999
101.16879739999999
101.18246199999999
101.19245369999999
101.20157659999998
...

Giving a delta print to see that it is very low:

83330
80961
73063
80566
....

The intent is to make x vary by speed units per second. In a second, the sum of all delta 's obtained must be 1e9, so the sum of all increments in x must be speed , but as I showed this is not what happens, if anyone can help me I appreciate it.

Answer:

I made some changes to the loop: The first big mistake is that I was skipping the design phase to do the calculations (it happens right after the logics() ), which is a big mistake as the rendering part takes a lot of time , the second was the way I calculated diff , the most accurate way to do that would be right before calling the 'logics(long delta)' method, before also calculating the before , so the logics() method looks like this:

@Override
public void logics() throws Exception{
    after =  System.nanoTime();
    diff = after - before;
    before = System.nanoTime();
    loop.logics(diff);
}

With these changes the movement is really good: using different speed values ​​: 1, 10 and 100 you can see that the x variation is close to the expected: it increases approximately speed units per second.

Scroll to Top