Player character slows when up or down input is held while moving

I used Input.get_vector() to get around having to make two separate inputs for my x and y values but if either up or down input is held while moving the players x velocity is lowered to 88. I could just bite the bullet and make two separate variables but I was just curious as to why this might be happening and how to circumvent it. Thanks.

Relevant Player Code

extends CharacterBody2D

var walk_speed = 125.0
var climb_speed = 100.0
var deceleration = 1.0
var acceleration = 1.0

var coyote = false
var last_floor = false

func _ready():
	add_to_group("player")
	$coyote_timer.wait_time = 5 / 60.0

func _physics_process(delta):
	var dir = Input.get_vector("left", "right", "up", "down")
	last_floor = is_on_floor()
	
	if dir.x < 0 and is_on_floor():
		$AnimatedSprite2D.flip_h = true
	elif dir.x > 0 and is_on_floor():
		$AnimatedSprite2D.flip_h = false
	
	#Walking
	if dir.x != 0 and is_on_floor():
		$AnimatedSprite2D.play("walk")
		velocity.x = lerp(velocity.x, dir.x * walk_speed, acceleration)
	elif is_on_floor():
		$AnimatedSprite2D.play("idle")
		velocity.x = lerp(velocity.x, 0.0, deceleration)
	print(velocity)
	move_and_slide()
	
	#Jumping
	if Input.is_action_just_pressed("action") and (is_on_floor() or !$coyote_timer.is_stopped()):
		velocity.y = -200
	if !is_on_floor() and !climbing:
		$AnimatedSprite2D.play("jump")
		velocity.y += 750 * delta

Hi,

get_vector will return a direction that will be diagonal if pressing both a horizontal and vertical input. A diagonal direction will have a smaller length on the x axis than a purely horizontal vector.
Let me show you my Paint skills to demonstrate this:

On the left side, the input is right only. On the right side, the input is both right and up. Both vectors (red arrows) are the same length, however, their x value is different, and that’s exactly what is happening here (at least that’s what I think).

To fix this, you can just use the get_axis method to calculate horizontal and vertical axis separately.

Let me know if that helps.

2 Likes