I'm writing a simple game with javascript/html5, and I'm trying to implement "gravity".
The code I have is sort of like this:
gravity = 4;
acceleration = 1.1;
function gameLoop(){
gravity = gravity*acceleration;
if (characterPositionY < 600)
characterPositionY = characterPositionY + gravity;
setTimeout(gameLoop,1000/30);
}
The figure "600" is the bottom of the screen, the "ground", if you will, where the player should stop falling.
Unfortunately, since the gravity makes the character fall by at least 4 pixels (and increasing) in each loop cycle... the character will often stop past, or before the ground. Like this, for example:
[1] characterPositionY is 590
-add 4-
[2] characterPositionY is 594
-add 4-
[3] characterPositionY is 598
-add 4-
[4] characterPositionY is 602
...past the ground.
I've never really made any games before, and I'm just making it all up as I go along. There are probably much better ways to go about this. So I'll appreciate any tips.
Thanks!