i am creating a 2d platformer in godot 4 and i am running into issues during finetuning of my jump mechanic. when i hold the jump button the character keeps jumping. i want the character only be able to jump again when releasing the jump button and also reseting the jump buffer as the player lands on the floor.
i created a gravity component which i import in my player.gd script which handles the jumping mechanic so i can reuse it for other scripts aswell.
# gravity_component.gd
@export var actor: Node2D
@export var jump_height : float = 75.0
@export var jump_time_to_peak : float = 0.5
@export var jump_time_to_descent : float = 0.35
@onready var jump_velocity : float = ((2.0 * jump_height) / jump_time_to_peak) * -1.0
@onready var bounce_velocity : float = ((jump_height) / jump_time_to_peak) * -1.0
@onready var float_velocity : float = ((jump_height) / jump_time_to_peak) * -1.0
@onready var jump_gravity : float = ((-2.0 * jump_height) / (pow(jump_time_to_peak, 2))) * -1.0
@onready var fall_gravity : float = ((-2.0 * jump_height) / (pow(jump_time_to_descent, 2))) * -1.0
func input_jump():
if Input.is_action_pressed("jump"):
actor.velocity.y = getJumpVelocity()
func float_jump():
if Input.is_action_just_released("jump") and actor.velocity.y < (getJumpVelocity() / 2):
actor.velocity.y = getFloatingVelocity()
now i can reuse this in my player.gd main script which looks like this:
# player.gd
var jump_available = true
var jump_buffer = false
func _physics_process(delta):
gravity_component.apply_gravity(delta)
handle_animations()
handle_movement(delta)
handle_jump()
func handle_jump():
# DONT MOVE_AND_SLIDE HERE NUB
if is_on_floor():
if jump_buffer:
gravity_component.input_jump()
jump_buffer = false
else:
jump_buffer = true
elif not is_on_floor():
gravity_component.float_jump()
state = JUMP
func handle_animations():
match state:
# some other code here
JUMP:
animatedSprite.play("jump")
animatedSprite.flip_h = DIRECTION == -1
_: # default
animatedSprite.play("idle")
i was also thinking of reseting the jump buffer once the player releases the jump button like this but i could not get it working
func resetJumpBuffer():
if jump_buffer && Input.is_action_just_released("jump"):
jump_buffer = true
full code can be found here:
https://gitlab.com/fiehra/dinolife