How to limit vector.x, if vector.y has reached maximum

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

Hello
I’m new at godot engine. I’m trying to make a space shooter game and I’ve encountered a little problem.
I am moving my ship with that code:

if button_up.is_pressed():`
	velocity += Vector2(acceleration, 0).rotated(rotation + deg2rad(-90))
move_and_slide(velocity)

I made it so ship moves to where it’s pointing and it works pretty fine. However when I’m moving to degrees between 1 and 89, 91 and 179 etc., both velocity.x and velocity.y keep rising until it reaches max_speed and that results in my ship moving directly 45, 135, 225 or 315 degrees and not where it’s pointing.
I want to make it so when for example velocity.x reaches max_speed, vector.y gets limited to its current value. Is it possible?

Thank you in advance and excuse me for my english

:bust_in_silhouette: Reply From: navett52

A crude way I can think to do it is just by some checks. Something like

var currentY = velocity.y
var currentX = velocity.x

# The code you currently have would go here

if velocity.x == maxspeed:
    velocity.y = currentY

# You would have the same logic again, just swap x and y

move_and_slide(velocity)

This may not work exactly if copy/pasted, but this general idea is what you could try. Store the old velocity, run your current code which is updating velocity, compare the new velocity with maxspeed, and if either is the same or greater than maxspeed you can reset the values to the old velocity.