Help with normalizing diagonal movement?

Godot Version

4.2.1

Question

Hello, I needed some help with how to make my character move the same speed diagonally as it does horizontally/vertically. I know this is a pretty common problem and I know I have to normalize my velocity, but I’m unsure of how to do that here. The physics in my game are a little more unconventional as I am making a space ship game where there is no friction and momentum is only changed from player input, so it’s a little hard to wrap my head around what to normalize and where. Here is my character code:

extends CharacterBody2D

var rotSpdL = 0
var rotSpdR = 0
var speed = 200
var reverse = 150
var strafe = 100
var topSpeed = 150
var topSpeed2 = -150
var reverseTopSpeed = 300
var strafeTopSpeed = 150

func _ready():
pass

func _physics_process(delta):
var forwSpd = Vector2(1, 0).rotated(rotation) * speed * delta
var backSpd = Vector2(-1, 0).rotated(rotation) * reverse * delta
var sideSpdL = Vector2(0, -1).rotated(rotation) * strafe * delta
var sideSpdR = Vector2(0, 1).rotated(rotation) * strafe * delta
if Input.is_action_pressed("left"):
	rotSpdL -= 0.5 * delta
	if rotSpdL <= -4 * delta:
		rotSpdL = -4 * delta
	rotation += rotSpdL
else:
	rotSpdL += 0.2 * delta
	if rotSpdL >= 0.00:
		rotSpdL = 0
	rotation += rotSpdL

if Input.is_action_pressed("right"):
	rotSpdR += 0.5 * delta
	if rotSpdR >= 4 * delta:
		rotSpdR = 4 * delta
	rotation += rotSpdR
else:
	rotSpdR -= 0.2 * delta
	if rotSpdR <= 0.00:
		rotSpdR = 0
	rotation += rotSpdR

if Input.is_action_pressed("forward"):
	velocity += forwSpd
if Input.is_action_pressed("backward"):
	velocity += backSpd
if Input.is_action_pressed("strafeL"):
	velocity += sideSpdL
if Input.is_action_pressed("strafeR"):
	velocity += sideSpdR


velocity.x = clamp(velocity.x, topSpeed2, topSpeed)
velocity.y = clamp(velocity.y, topSpeed2, topSpeed)
move_and_slide()

if Input.is_action_just_pressed("quit"):
	get_tree().quit()

As it shows, I want my velocity to be no higher than 150, but it goes up to about 210ish when moving diagonal. I basically just want to figure out how to fix that. I’ve tried quite a few things but nothing seems to work. Do I normalize the velocity itself, the forwSpd variable, or maybe both? And where? Or I am thinking about this all wrong? I apologize for the surely crude code, and will take any advice if there is something obvious, even if I’m told to just nuke the code and start rom scratch. Thank you for taking the time to read this.

this seems like the culprit. You’ll want to operate over all axis at the same time as often as possible for normal movement

velocity = velocity.clampf(topSpeed2, topSpeed)

Vector2.clamp() will clamp each component individually, so the result would be the same. You should use limit_length() for this:

velocity = velocity.limit_length(topSpeed)

This fixed it! That makes sense! I figured it was something simple. Thank you for your help!