Search code examples
2dgodot

how do i make my character slow down after jumping?


after my character jumps it goes down really quickly like after i jump i wanna go down slowly and if there is a simple solution then i will appreciate if you type it in the comments here is the code

extends KinematicBody2D


var speed = Vector2(500, 2500)
var gravity = 10000
var friction = 0.1
var acceleration = 0.2
var velocity = Vector2.ZERO


func _physics_process(delta: float) -> void:
    var dir = get_direction()
    var is_jump_interupted = Input.is_action_just_released("jump") and velocity.y < 0.0
    velocity = calculate_velocity(velocity, dir, is_jump_interupted, speed, delta)
    velocity = move_and_slide(velocity, Vector2.UP)
    print(velocity)


func get_direction():
    return Vector2(
        Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left"),
        -1.0 if Input.is_action_just_pressed("jump") and is_on_floor() else 0.0
    )

func calculate_velocity(curVelocity, dir, is_jump_interupted, speed, delta):
    var out = Vector2.ZERO

    if dir.x != 0:
        out.x = lerp(curVelocity.x, dir.x * speed.x, acceleration)
    else:
        out.x = lerp(curVelocity.x, 0, friction)

    if(dir.y == -1.0): # Jumping
        out.y = dir.y * speed.y
    else: # Falling
        out.y = curVelocity.y + (gravity * delta)

    if(is_jump_interupted): # jump key release
        out.y = 0.0 + (gravity * delta)

    return out```

Solution

  • I guess you want the character to 'float' down, but have the jump up remain at the same speed. This small change should do it:

    if(dir.y == -1.0): # Jumping
        out.y = dir.y * speed.y
    elif curVelocity.y > 0: # Falling down
        out.y = curVelocity.y + (floating * delta)
    else: # Flying up
        out.y = curVelocity.y + (gravity * delta)
    

    Floating is a constant smaller than your gravity constant, eg. 500