-1
\$\begingroup\$

I'm trying to calculate object speed from delta time, to get object reaching the same distance in same time on all devices.

What I did:

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

From that I'm getting deltaTime:

  • 2.2789123E8 on my old Galaxy Ace S5830i

  • 2.7855414E8 on my tablet A7600-F

And then I do this calculation:

float calculation = screenWidth/2 * deltaTime; //My game is in landscape mode
int speed = Math.round(calculation); //speed represents pixels per update

Which should give speed that half of the screen is reached per 1 second, regardless on device updates (fps). It should be small number, about 10-20, but calculation results in

  • 546 on Ace
  • 1782 on tablet

What to do with that? As I said, if I set speed to fx. 11, it's reaching about half of the screen in my game on tablet. So why are these number's so large?

Ed: Ace width = 480, tablet width = 1280;

\$\endgroup\$
  • \$\begingroup\$ Can you please add the value of screenWidth? Your code seems fine to me. Can you limit the calls to 60Hz? Maybe rounding errors. \$\endgroup\$ – Benedikt S. Vogler Dec 6 '15 at 12:35
  • \$\begingroup\$ Yes widths are 1280 (tablet) and 480 (ace). Which calls exactly do you mean? \$\endgroup\$ – johnyX Dec 6 '15 at 12:57
  • \$\begingroup\$ the code run's at the fastest possible way which drains the battery of the device. You should limit it to 60 calls per second. Delta should then be about 16.67. Unfortunately I can not find a good guide on this topic on this game development stack exchange. \$\endgroup\$ – Benedikt S. Vogler Dec 6 '15 at 17:05
1
\$\begingroup\$

Something is wrong with your delta time. 2.2789123*10^8 are equal to 7.22 years for one frame. I think you don't initialize oldTimeSinceStart then read deltaTime after one frame. You should init oldTimeSinceStart with System.nanoTime();

\$\endgroup\$
  • \$\begingroup\$ Recalculated delta, it returns now 0.03355443. So recalculations are: 21px per update on tablet and 86px per update on Z3 Compact. But it's still a big difference on Z3 (86 is extreme big) \$\endgroup\$ – johnyX Dec 6 '15 at 17:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.