Godot Version
4.2
Question
How to invert gravity in Godot
Why doesnt spacebar invert gravity, it just jumps: extends CharacterBody2D
var speed = 600 # Horizontal movement speed
var ngraivty = -1000;
var gravity = 1000 # Gravity strength (pixels per second squared)
func _physics_process(delta):
# Apply gravity
if not is_on_floor():
velocity.y += gravity * delta
# Horizontal movement input
var horizontal_input = Vector2.ZERO
if Input.is_action_pressed("a"):
horizontal_input.x -= 1
if Input.is_action_pressed("d"):
horizontal_input.x += 1
velocity.x = horizontal_input.x * speed
# Jump input
if Input.is_action_just_pressed("space") and is_on_floor():
velocity.y += ngraivty;
move_and_slide()
Because that code does not actually invert the gravity.
Keep in mind that _physics_process
is called sixty times a second. Say that the character is on the floor and the player pressed the space bar:
# Jump input
if Input.is_action_just_pressed("space") and is_on_floor():
velocity.y += ngraivty;
In that section of code, the character’s y-velocity is set to -1000. The character moves up and is no longer on the floor after move_and_slide
is called. 1/60th of a second later, _physics_process
is called again. Code is executed from the top:
if not is_on_floor():
velocity.y += gravity * delta
The character is no longer on the floor, so we enter this if-statement and the character’s velocity is immediately set back to 1000 (i.e. moving down.) That is why your character appears to jump-- a sudden upward movement that lasts for approximately one frame, followed by an immediate drop down.
1 Like