Kinematic Character is jumping higher/lower every other jump

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By MugaSofer

I’m right at the beginning of putting together a simple platformer with a KinematicBody2D main character. I’ve only gotten as far as adding basic movement controls, only to run up against a very strange bug - the character’s jump height is inconsistent. First they jump too high, then too low, then too high again, alternating between high/low jumps.

This behavior grows more severe the higher I set them to jump; if set high enough, they rocket off the screen first time you jump, then barely jump at all, then rocket off screen again, then barely jump at all again, and so on. I’ve tried disabling the animations and switching between move_and_slide() and move_and_collide() without effect. I also tried multiplying their movements by the delta, which didn’t fix the bug but it’s good practice so I left it in.

The character themselves is a simple KinematicBody2D with a sprite, an AnimationPlayer, a CollisionObject2D (a CapsuleShape2D around the character), and a Raycast2D straight down to detect the ground.

Here’s the code:

extends KinematicBody2D

var agility = 1
var velocity = Vector2(0,0)
func _physics_process(delta):
	if $groundDetector.is_colliding():
		velocity.x = lerp(velocity.x, 0, .1)

		if Input.is_action_just_pressed("ui_up"):
			var jump_power = 300 
			velocity += Vector2(0,agility * -jump_power)
		if Input.is_action_pressed("ui_left") and $groundDetector.is_colliding():
			velocity +=  Vector2(agility * -600 * delta,0)
		if Input.is_action_pressed("ui_right") and $groundDetector.is_colliding():
			velocity +=  Vector2(agility * 600 * delta,0)
		velocity += Vector2(0, 100* delta)


if $groundDetector.is_colliding():
    velocity.x = lerp(velocity.x, 0, .1)
    velocity.y = 0

timothybrentwood | 2021-05-07 15:46

Ah, thank you! Of course, it was retaining some of the “falling” velocity after hitting the ground, invisible because it’s a kinematic body. You’re right, that solved it.

MugaSofer | 2021-05-12 13:20

No problem! It’s a lot easier to find mistakes in other people’s code rather than your own haha

timothybrentwood | 2021-05-12 13:37