• 2D
  • How to use normalized() efficiently to remove faster diagonal movement?

Im working on a movement system with acceleration, and it appears that the player is moving faster when two directions are held diagonally, heres the code i have right now:

extends KinematicBody2D

var velocity = Vector2()

var acceleration = 20
var max_speed = 200

func _physics_process(delta):
	get_input()
	move_and_collide(velocity * delta)

func get_input():
	if Input.is_action_pressed("move_right"):
		velocity.x = min(velocity.x + acceleration, max_speed)
	elif Input.is_action_pressed("move_left"):
		velocity.x = max(velocity.x - acceleration, -max_speed)
	else:
		velocity.x = lerp(velocity.x, 0, 0.05)
	if Input.is_action_pressed("move_down"):
		velocity.y = min(velocity.y + acceleration, max_speed)
	elif Input.is_action_pressed("move_up"):
		velocity.y = max(velocity.y - acceleration, -max_speed)
	else:
		velocity.y = lerp(velocity.y, 0, 0.05)

so far i have tried rewriting everything a couple of times, but the furthest i got to how i wanted it was this, this one only has the diagonal movement remaining.

how do i normalize the value of the velocity so that the player doesnt move faster diagonally?

You could try with:

velocity =  velocity.normalized() * min(velocity.length(), max_speed)

@xyz said: You could try with:

velocity =  velocity.normalized() * min(velocity.length(), max_speed)

that fixed it when i put it above the move and collide line. I never thought of using min like that, thats a bunch!