Player is sometimes bouncing too high after hitting the ground once

extends CharacterBody2D

@export var jump_count : int = 0
var current_jump_count : int
@export var SPEED = 150.0
@export var JUMP_VELOCITY = -200.0

Get the gravity from the project settings to be synced with RigidBody nodes.

var gravity = ProjectSettings.get_setting(“physics/2d/default_gravity”)

func _physics_process(delta):
if not is_on_floor():
velocity.y += gravity * delta
if Input.is_action_just_pressed(“spacebar”) and is_on_floor():
velocity.y = JUMP_VELOCITY
current_jump_count += 1

var collision = move_and_collide(velocity * delta)
if collision and current_jump_count >= 1 :
	velocity = velocity.bounce(collision.get_normal())
	velocity.y *= 2
	jump_count -= 1
	

if current_jump_count and jump_count >= 1:
	current_jump_count -= 1
	jump_count -= 1
	velocity.y = 0


var direction = Input.get_axis("left", "right")
if direction:
	velocity.x = direction * SPEED
else:
	velocity.x = move_toward(velocity.x, 0, SPEED)

move_and_slide()

Question:
My player is supposed to bounce after hitting the ground once, but for some reason after moving it randomly bounces WAY higher than its supposed to. How do i stop that?

There are two points where your velocity.y is increased:

velocity.y = JUMP_VELOCITY

and

velocity.y *= 2

My guess is that velocity is somehow updated after move_and_slide() and that gets multiplied. You’d need to debug this. For example, you can put a breakpoint at

jump_count -= 1

And see that value gets assigned to velocity.y

Alternatively, you could put this below jump_count -= 1:

if velocity.y < -10:
  print_debug("I am jumping! Velocity = " + str(velocity.y))

To stop it, I’d put more checks in

if collision and current_jump_count >= 1 :

For example, check that the velocity.y is a positive number, meaning the player is falling down.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.