I am building a flappy bird game but i have a problem that when i spam the jump key the player goes extremly high. Please help
here is my code:
extends CharacterBody2D
var speed = 400
var jump_force = 1000
func _physics_process(delta):
var direction = Input.get_axis(“left”,“right”)
if not is_on_floor():
velocity.y += 980 * delta
if direction:
velocity.x = speed * direction
if direction == -1:
$Sprite2D.flip_h = false
if direction == 1:
$Sprite2D.flip_h = true
else:
velocity.x = 0
if Input.is_action_just_pressed(“jump”):
velocity.y -= jump_force
Without air resistance jumping height is directly proportional to the square of the jumping velocity, so adding multiple jump velocities together can make the character jump insanely high.
You can prevent this behaviour by limiting the velocity after jumping.
It’s an arbitraty constant value, which you can define or replace with anything you want. For example:
const MIN_VELOCITY_Y = -1500.0
By the way, after my initial answer I realized that you could also solve the problem by making it so that each jump adds a fixed amound of kinetic energy. That way the jump velocity isn’t limited, but it feels more natural.
const JUMP_ENERGY = 1000000.0
const MAX_JUMP_VELOCITY = -1000.0
if Input.is_action_just_pressed(“jump”):
var energy = velocity.y * velocity.y
energy += JUMP_ENERGY
velocity.y = minf(MAX_JUMP_VELOCITY, -sqrt(energy))