Wy dont my character jump normally?

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

So I tried to make my character jump (This is probably horrible code, this is my first time coding) But sometime it just hop a little when I pressed jump.

This is the script for my KinematicBody2D (GDScript)

    extends KinematicBody2D

    const GRAVITY = 2000
    const WALK_SPEED = 750
    const ACCELERATION = 50
    const JUMP_SPEED = -1000
    var velocity = Vector2()

    func _physics_process(delta):

        if !is_on_floor():
	        velocity.y += delta * GRAVITY

        if Input.is_action_pressed("ui_left"):
	        velocity.x = velocity.x + -ACCELERATION
        elif Input.is_action_pressed("ui_right"):
	        velocity.x = velocity.x + ACCELERATION
        elif velocity.x != 0:
	        if velocity.x > 0:
		        velocity.x = velocity.x + -ACCELERATION
	        else:
		        velocity.x = velocity.x + ACCELERATION
        else:
	        velocity.x = 0
	
        if velocity.x > WALK_SPEED:
	        velocity.x = WALK_SPEED
        elif velocity.x < -WALK_SPEED:
	        velocity.x = -WALK_SPEED

        if is_on_ceiling():
	        velocity.y = -velocity.y
	
        if Input.is_action_just_pressed("ui_up") and is_on_floor():
	        velocity.y = velocity.y + JUMP_SPEED

        move_and_slide(velocity, Vector2(0, -1))
:bust_in_silhouette: Reply From: GDYEE

It should set the y velocity to the jump speed of that instead of adding so the jump height will always be the same

velocity.y = JUMP_SPEED

:bust_in_silhouette: Reply From: NIRMAL KUMAR R
move_and_slide() returns a Vector2 value with specified up direction, So try assigning velocity = move_and_slide()
:bust_in_silhouette: Reply From: Ninfur

The problem is that when the character land, the vertical velocity will be at some positive value, lets say 732, due to gravity, and it is never set to 0. When you later try to jump, you add the jump force (-1000) to the existing velocity. So velocity.y = 732 - 1000 = -268. You now jump with a force of -268 instead of -1000.

To fix this you must either set the vertical velocity to 0 while the character is on floor, or set the vertical velocity to a fixed value when jumping instead of adding it to the current velocity.

if !is_on_floor():
    velocity.y += delta * GRAVITY
else:
    velocity.y = 0

or

if Input.is_action_just_pressed("ui_up") and is_on_floor():
    velocity.y = JUMP_SPEED