How to change the 2D gravity direction?

The trick is to change the code so that no part of it uses the x or y components of velocity directly.

Applying gravity

velocity += gravity * delta * gravity_dir

Limiting fall speed

var y_speed = gravity_dir.dot(velocity)
if y_speed > max_fall_speed:
    velocity += (max_fall_speed - y_speed) * gravity_dir

Running without acceleration

var right_vector = gravity_dir.orthogonal()
if direction and dTrue:
    velocity = velocity.slide(right_vector) + direction * SPEED * right_vector
else:
    velocity = velocity.slide(right_vector)

Jumping

if Input.is_action_just_pressed("ui_accept") and is_on_floor():
    velocity = velocity.slide(gravity_dir) + gravity_dir * JUMP_VELOCITY
if Input.is_action_just_released("ui_accept") and velocity.dot(gravity_dir) < 0.0:
    velocity = velocity.slide(gravity_dir)

Wall jump

if is_on_wall_only() and direction and Input.is_action_just_pressed("ui_accept"):
    velocity = -450.0 * direction * right_vector - 120 * gravity_dir

Moving the character

up_direction = -gravity_dir
move_and_slide()

I haven’t tested all this code, so I hope I didn’t make any mistakes.

3 Likes