I'm looking for an easy, beginner friendly way to do gravity in a platformer.
I've looked into Box2D tutorials, but they all seem very complicated.

All I want is a class that takes into account if my player is grounded, or airborn, and a nice little curve as he jumps. I know this shouldn't be more than a few lines of code, and learning a library seems excessive.

@Byte56 Allright, then I use a timer to update this every so and so milliseconds?
–
hustlerincJul 20 '12 at 0:19

It'll be in the update loop for your character. Whenever your character's position is updated, this gets run. If you don't have an answer before I get back from work, I'll give you a real answer.
–
Byte56♦Jul 20 '12 at 0:24

@Byte56 I would appreciate that, trying to make my own function right now but it's not going well. Stuck at the timer, I guess I'll figure it out sooner or later, but a complete example would be nice. =)
–
hustlerincJul 20 '12 at 0:40

1 Answer
1

So, implementing gravity has some prerequisites. A big one is a time keeping system. One good read for time systems is Fix Your Timestep! by gafferongames.com. The time system ties in tightly to the update loop. See deWITTERS Gameloop for info on implementing an update loop (which covers time step too). Once you have an update loop with a delta time for each iteration, you're pretty much ready.

Thanks for the links. I haven't figured out how to do the timestep yet tho. lastUpdate and now is always the same. Also adding milliseconds to calculate next frame is messing up.
–
hustlerincJul 20 '12 at 2:41

1

I suggest finding a working example out on the net somewhere. I'm sure there are plenty of them. When you start with something that works, you have a much easier time knowing where it's going wrong.
–
Byte56♦Jul 20 '12 at 2:45

How exactly does this work? velocity.y (jump force) += gravity * delta (every frame or does deltatime increment to represent the time for the entire jump?). What is a good number for gravity, I have an fps of 25, which means my deltatime would be 40 at best, this gives a pretty strong gravity on 32x32 px.
–
hustlerincJul 20 '12 at 5:00

When jumping, set the upward velocity to some positive value. Then every frame the gravity*delta will take a bit more away from that velocity. Eventually reaching 0 velocity. That's the peak of the jump. The velocity will then go negative and continue to do so until your character reaches the ground, at which time you'll set velocity to 0 and gravity to 0. A good number for gravity is something you'll have to play with. It depends on the units you're using in your game, is it all pixels? How many pixels per meter (in game)? For example, if it was 1 pixel per meter, you'd use 9.8 for gravity.
–
Byte56♦Jul 20 '12 at 5:06