Hi guys, i’m new in game programming, in i would like to undestand some concept before to write wrong code
i would like to know wich is the strategy that you use to calculate the movement of a sprite in a 2D world
consider that i have implemented a loop cicle that has the target to mantain the UPS costant and that is able also to lost some
frame to rich the target of the number of UPS/seconds
now my loop manage a game that is an interface that make separately
game.updateGame();
game.renderGame();
game.paintScreen();
obvisuly to calculate the movement i should pass a parameter to updateGame() method => updateGame(parameter)
that could be time in the way that i can conside the movement based on a concept of pixel/seconds
and mantain for any sprite a variable, called speed, that indicate the pixel/second that i want to move that sprite
so in my logic when i have to calculate the next position, it should be NewX = PreviousX+speed*parameter
but in my loop to mantain costant the update i can skip some frames, and repeat the game logic more time,
and in this case i can not pass the correct parameter to the updateGame() method
what do u think
1)if i pass my variable period to the updateGame(parameter) variable parameter
2)if i try to dipend my logic for the calculation of the movement from same function that dipend from the time and the UPS
3)if i create a mixed strategy: depend from time in the normal update depend from the period in the update executed for the skip frame?
will be well appreciated every experience shared with me, thanks
this is the code of the loop:
int NO_DELAYS_PER_YIELD = 16;
/* Number of frames with a delay of 0 ms before the animation thread yields
to other running threads. */
int MAX_FRAME_SKIPS = 5; ;
// no. of frames that can be skipped in any one animation loop
// i.e the games state is updated but not rendered
long period = (1000/TARGET_FRAME_SECOND) *1000000L; // period in ms -> nano
beforeTime = System.nanoTime();
while(!gameStatus.isStop()){
game.updateGame();
game.renderGame();
game.paintScreen();
afterTime = System.nanoTime();
timeDiff = afterTime - beforeTime;
sleepTime = (period - timeDiff) - overSleepTime;
if (sleepTime > 0) { // some time left in this cycle
try {
Thread.sleep(sleepTime/1000000L); // nano -> ms
}
catch(InterruptedException ex){}
overSleepTime = (System.nanoTime() - afterTime) - sleepTime;
}else { // sleepTime <= 0; the frame took longer than the period
excess -= sleepTime; // store excess time value
overSleepTime = 0L;
if (++noDelays >= NO_DELAYS_PER_YIELD) {
Thread.yield(); // give another thread a chance to run
noDelays = 0;
}
}
beforeTime = System.nanoTime();
/* If frame animation is taking too long, update game state without render it, to get the updates/sec
int skips = 0;
while((excess > period) && (skips < MAX_FRAME_SKIPS)) {
excess -= period;
game.updateGame(); // update state but don't render
skips++;
}
}