How to code smooth jump instead of teleporting in the air

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

my code:

func _physics_process(delta):
var motion = Vector2()
motion = move_and_slide(motion, Vector2.UP)
velocity.y += gravity * delta
if Input.is_action_pressed(“ui_right”):
motion.x = 400
elif Input.is_action_pressed(“ui_left”):
motion.x = -400
elif Input.is_action_pressed(“jump”) and is_on_floor():
motion.y = -8000
else:
motion.x = 0
motion.y = 0
gravity = 400
move_and_slide(motion)

cos my jump teleports me to the air then slowly falls down

:bust_in_silhouette: Reply From: chugwig

Your answer is right there in front of you, your jump is jerky but your fall isn’t. What’s the difference between the way you implement those two features?

TLDT: Your falling is implemented with an acceleration but your jumping is implemented by instantly setting the velocity. So come up with some jump_acceleration and a max_jump_speed (probably -8000 based on your code) and implement a process very similar to what you’re doing with gravity except capping the max speed (which you probably want in the opposite direction for gravity as well, depending on how far the character can fall and how high your gravity is)

:bust_in_silhouette: Reply From: Magso

Bring motion.y back to the gravity amount gradually from a lower value.

elif Input.is_action_pressed("jump") and is_on_floor():
    motion.y = -800 #lower value
    var lerp_amount = 0.0
    while lerp_amount < 1:
        lerp_amount += delta
        motion.y = lerp(-800, gravity, lerp_amount)
        yield(get_tree(), "idle_frame")

Thank you!

I’d like to add that after I used this code in mine, my character seemed to have a unintended delay/cooldown on his jump.

I think is_on_floor() wasn’t being updated on time because the while loop was slowing the code by waiting the condition to end.

And my character reached the ground before the loop was done.

Writing this on the next line afteryield() fixed it.

if is_on_floor():
	break

Resulting in

while lerp_amount < 1:
    lerp_amount += delta
    motion.y = lerp(-800, gravity, lerp_amount)
    yield(get_tree(), "idle_frame")

    if is_on_floor():
        break

Random_Furry | 2022-11-05 17:09