kinematicbody2d goes shooting off into the stratosphere whenever I try to move

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

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
:bust_in_silhouette: Reply From: p7f

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

It worked, thanks!

exuin | 2020-09-08 04:35