how can i jump while moving?

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

I can’t figure out how to jump while I am moving but I can’t figure out how. Here is the code,

extends KinematicBody2D

const GRAVITY = 300.0
const WALK_SPEED = 500.0
var velocity: Vector2 = Vector2.ZERO

func _physics_process(delta):
velocity.y += delta * GRAVITY

if Input.is_action_pressed("left"):
	velocity.x = -WALK_SPEED
elif Input.is_action_pressed("right"):
	velocity.x =  WALK_SPEED
elif Input.is_action_just_pressed("jump"):
	velocity.y = -WALK_SPEED
else:
	velocity.x = 0

# "move_and_slide" already takes delta time into account.
move_and_slide(velocity)
:bust_in_silhouette: Reply From: godot_dev_

What if instead of using elif you just use if (see below), that way both contitions can be met on the same frame so you can hold right/left and jump on the same physics update

func physicsprocess(delta):
    velocity.y += delta * GRAVITY
    if Input.is_action_pressed("left"):
        velocity.x = -WALK_SPEED
    elif Input.is_action_pressed("right"):
        velocity.x =  WALK_SPEED
    else:
        velocity.x = 0
    if Input.is_action_just_pressed("jump"):
        velocity.y = -WALK_SPEED
    
# "move_and_slide" already takes delta time into account.
move_and_slide(velocity)

It works, thank you.

Zandereal | 2023-06-23 12:32