Playing with Gravity

I’m coding gravity for a 2D platformer. Currently a set amount of gravity is just being subtracted from the player’s vertical speed before reaching a terminal velocity, which works fine. When jumping, the character is going up at a set speed then turns around and begins going down at the same speed.

But if I throw a ball in the air in real life, it seems to slow down as it comes closer to the apex and then kinda hovers there for a moment before gradually picking up downward speed on its way down again. — Any ideas how I could code gravity that works more like this?

Berenger is totally right :wink:

However accelerated movement (like gravity) should be applied in FixedUpdate(). I know it’s usually only used with the internal physics system (Rigidbody), but for integral computations you should use a constant amount of steps per sec. or you will have a movement that is frame-dependent even when you use deltaTime. That’s because gravity produces a quadratic movement which can’t be linearly scaled.

// C#
Vector3 gravity = new Vector3(0,-9.81f,0);
Vector3 velocity;

void FixedUpdate()
    velocity += gravity * Time.deltaTime;
    transform.position += velocity * Time.deltaTime;

Your controlling logic should still be in Update() which is called each visual frame. FixedUpdate is guaranteed to be called a fix amount of times per sec which is configured in the Time settings (Edit->Project Settings->Time->Fixed Timestep). 0.02 == 50fps (1/0.02).

Linear movement can still be done in Update() if you want, but usually it’s better to use only one velocity. You would check the input in Update and change the velocity according to the input. FixedUpdate would then perform the movement.

Everything depends on how you code your physic system. Basically, from what I know, you need a velocity vector, which is “where I want to be at the next frame”. Then, you need to apply forces to that vector every frame. Gravity is a constant, and my brain is giving me a name “Plank” with a number 9.81, and I think that’s some memory from my physics lesson’s in highschool ^^. The jump however, will be a strong force upward only once.