ID:1286148
 
(See the best response by Kaiochao.)
Alright so here's my question - how would you go about limiting two variables to a common maximum? As in, the sum of X and Y cannot exceed M.

I ask because I started creating a space-ship movement system, where pressing the keys slowly changes your momentum. It's split into x-momentum and y-momentum. I like it because you can get the ship going at any angle and stop pressing the keys, and the ship will continue at the same angle (like in real outer space :D)

Anyway, the problem is that limiting each separately allows the ship to travel twice as fast if it is going diagonally. So if the max speed is 8, you could only go due north at 8 pixels per step. But, you could also go north at 8 pixels AND east at 8 pixels, and thus travel 16 pixels per step.

I was thinking of changing the whole thing, by instead having one speed variable, and an angle. But is there any other way?
Best response
I use a simple speed limit for my space ships.
// this is to accelerate (when the thrust key is held)
vx += accel * sin(angle)
vy += accel * cos(angle)

// basic speed limiting:
// if moving faster than limit, scale to limit
var speed = sqrt(vx * vx + vy * vy)
if(speed > max_speed)
// we're dividing by speed to make a unit vector
// and multiplying by max_speed so the end result is
// a vector with a magnitude of max_speed
var scale = max_speed / speed
vx *= scale
vy *= scale
Man, I shoulda payed more attention to this in high school...thanks for refreshing my memory :D