views:

147

answers:

4

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!

A: 
function gameLoop(){

  gravity = gravity*acceleration;

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

  setTimeout(gameLoop,1000/30);

}

Maybe this would help?

Erkan Haspulat
+5  A: 

Change your test to something like:

if (characterPositionY + gravity < 600)
    characterPositionY = characterPositionY + gravity;
else
    characterPositionY = 600;
Paul
You could also use the min function: characterPositionY = min(characterPositionY + gravity, 600);It takes up less code and one less operation on the CPU.
mattbasta
A: 
 if (characterPositionY < 600) {
     characterPositionY = characterPositionY + gravity;
     if (characterPositionY > 600) characterPositionY = 600;
 }
MiffTheFox
A: 
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);

}

The gravity var really represents gravity's contribution to Y movement. Consider renaming it to something like fallSpeed.

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

I hope this helps.

Arex