I am writing a simple game with javascript / html5 and I am trying to implement "gravity".
The code I have is something 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 want, where the player must stop falling.
Unfortunately, since gravity causes the character to fall by at least 4 pixels (and increase) in each cycle of the cycle ... the character often stops past or in front of the ground. For example, for example:
[1] characterPositionY is 590
-add 4 -
[2] characterPositionY - 594
-add 4 -
[3] characterPositionY - 598
-add 4 -
[4] characterPositionY - 602
... past the ground.
I have never done any games before, and I just do it all when I go. There are probably much better ways to do this.