Gravity not working properly in Javascript / HTML5

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.

+3
4

- :

if (characterPositionY + gravity < 600)
    characterPositionY = characterPositionY + gravity;
else
    characterPositionY = 600;
+5
function gameLoop(){

  gravity = gravity*acceleration;

  if (characterPositionY < 600-gravity)
    characterPositionY = characterPositionY + gravity;

  setTimeout(gameLoop,1000/30);

}

, ?

0
 if (characterPositionY < 600) {
     characterPositionY = characterPositionY + gravity;
     if (characterPositionY > 600) characterPositionY = 600;
 }
0
source
gravity = 0;  /* rate of change of position due to grav*/
acceleration = .4; /* rate  of change of grav*/


function gameLoop(){

  if (characterPositionY < 600)/* above ground*/
  {
    gravity = gravity + acceleration; /*increase speed of drop*/
    characterPositionY = characterPositionY + gravity; /*apply speed to position*/
  }
  if (characterPositionY >= 600)/*at or below ground*/
  {
    characterPositionY = 600; /*set on ground if character has 'clipped' through*/ 
    gravity = 0; /*touching the ground has stopped Y movement due to gravity*/
  }

  setTimeout(gameLoop,1000/30);

}

Gravitational weight really represents the gravitational contribution to the Y movement. Try renaming it something like fallSpeed.

Also note that the variable var, the acceleration is added to the gravity. This more accurately means constant acceleration. You can also consider renaming acceleration to gravAcceleration.

Hope this helps.

0
source

Source: https://habr.com/ru/post/1723591/


All Articles