Jump into the game
I am doing a 2nd side scroller and for life I can't jump to work. This is how I do the movement left and right:
for(var i = 0; i < time; i++)
newVelocityX = (oldVelocityX + accelerationX) * frictionX;
then update my player's position.
positionX = oldPositionX + newVelocityX;
This works great and the "time" variable only has the number of ms since I last ran the function. Friction works great and I'm happy that everything is good in the X direction. This is what I have in the Y direction:
for(var i = 0; i < time; i++) {
accelerationY += gravityAccelerationY;
newVelocityY = oldVelocityY + accelerationY;
}
The object falls due to gravity just fine. If I set the acceleration to negative Y when the user presses the up arrow, I can even make the player jump, but on a fast computer they jump very high and on an old computer they jump very low. I'm not sure how to fix this, I thought I was already explaining this by putting it in a loop like I did.
source to share
You will need to do a few things in order to change the code to work properly. There are many bugs / performance in the code you posted.
Here's some code to create the basics of the game.
Example code for the jump:
if (jump) {
velocityY = -jumpHeightSquared; // assuming positive Y is downward, and you are jumping upward
}
velocityY += gravityAccelerationY * time;
positionY += velocityY * time;
if (positionY > 0) {
positionY = 0; // assuming the ground is at height 0
velocityY = 0;
}
Example code to move sideways:
velocityX += accelerationX * time; velocityX *= Math.pow(frictionX, time); positionX += velocityX * time;
Some comments on the code:
Velocity and position variables should keep their values ββbetween frames (I assume you figured this out).
gravityAccelerationY and frictionX are constant values ββif gravity or friction has not changed.
Where I replaced your for loops with * time
, using a single multiplication would be faster than a loop. The only difference would be low frame rates or high acceleration rates, where acceleration seemingly "sped up" from what it should be. You shouldn't have a problem with this.
source to share