0 votes

See title.
Here is the code I have controlling the character. Also, after the character disappears off-screen, the debug window hangs and refuses to close.

extends KinematicBody2D

const WALK_SPEED = 100
const RUN_SPEED = 200
const JUMP_STRENGTH = 100
const GRAVITY = 10

var velocity = Vector2()

func get_input():
    velocity.x = 0
    if Input.is_action_pressed("ui_right"):
        velocity.x += 1
    if Input.is_action_pressed("ui_left"):
        velocity.x -= 1
    if is_running:
        velocity *= RUN_SPEED
    else:
        velocity *= WALK_SPEED

func _physics_process(delta):
    get_input()
    velocity.y += GRAVITY * delta
    velocity = move_and_slide(velocity, Vector2.UP)
    if is_on_floor() and Input.is_action_just_pressed("ui_up"):
        velocity.y = -JUMP_STRENGTH
in Engine by (8,544 points)

1 Answer

0 votes
Best answer

The problem is that you are multiplying velocity *= RUN_SPEED... that velocity includes the y component, which in _physics_process is added with GRAVITY each frame.

So every frame, you add GRAVITY*delta to velocity.y and multiply it by RUN_SPEED or WALK_SPEED, as one of those cases will always be executed regardless if you are pressing or not a key. My suggestion is to only multiply x component of velocity, as RUN_SPEED and WALK_SPEED should only modify that component:

func get_input():
    velocity.x = 0
    if Input.is_action_pressed("ui_right"):
        velocity.x += 1
    if Input.is_action_pressed("ui_left"):
        velocity.x -= 1
    if is_running:
        velocity.x *= RUN_SPEED #only x component
    else:
        velocity.x *= WALK_SPEED #only x component
by (3,501 points)
selected by

It worked, thanks!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.