Wednesday, October 7, 2015

android - How to implement jump in a 2d game?


I am trying to implement jump in a game I have written for android using canvas. I have referred this tutorial for implementing jump. My code is like


if(jumpKeyPressed){

jumpVel = -initialMomentum;
state = "jumping";
}
if(state == "jumping"){
jumpVel += gravity * deltaTime / 2;
loc.y += jumpVel * deltaTime;
jumpVel += gravity * deltaTime / 2;
}

Even after tweaking gravity and initialMomentum, character is jumping too slow (seems like stuck at ground). I have read many posts but I am not able to figure out what am I doing wrong here?



Edit: Video



Answer



My answer is based on Lolums' answer. His logic is good, especially if you are making a simulation of something with realism. But Philipp points out something important as well: correct physics do not typically translate well to platform games.


The take-away is that you should apply the idea of gravity velocity_y -= gravity * delta_time but you should not be afraid to use numbers that seem unrealistic. The ones you use will likely be higher than you'd expect by studying the real world, sometimes much higher. Case in point, consider Super Mario World.




  • When jumping regularly, Mario experienced a gravity of 67.82 m/s^2 (6.9 times Earth gravity). Here he had a push-off velocity of 17.36 m/s.

  • When high-jumping, Mario experienced a gravity of 34.79 m/s^2 (3.5 times Earth gravity). Here he had a push-off velocity of 15.21 m/s.

  • When falling off a ledge, Mario experienced a gravity of 55.88 m/s^2 (5.7 times Earth gravity).

  • As for running, Mario seemed to follow a perfectly constant run velocity pattern (as is expected, really). When walking, he moved at a speed of about 3.7 m/s, and when running, moved at a speed of about 9.1 m/s.




Source: http://hamaluik.com/posts/super-mario-world-physics/


Almost seven times Earth's gravity, under some conditions. And for that matter, note how inconsistent the acceleration values are. This violates many laws of physics, and that's okay.


My advice: Apply the basic model of gravity as you know it to exist, and then test your game. Play with the numbers. The force gravity in Castlevania 4 feels very, very strong. The gravity in Symphony of the Night doesn't. They're both excellent platform games, because the developers experimented and found what worked for their games.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...