Constraining maximum movement speed on a rigidbody on certain axes.

Hello

I’m trying to create a game where ive got a character flying through some streets, i’ve got a problem though.

I’ve written some code that uses the “rigidbody.velocity.magnitude” to limit the maximum speed, as i dont want to be able to accelerate for infinity.

    if(rigidbody.velocity.magnitude < maxspeed){
		rigidbody.AddForce(transform.rotation * Vector3.up * 1);
		rigidbody.AddForce(transform.rotation * Vector3.right * horizontal);
		rigidbody.AddForce(transform.rotation * Vector3.forward * -vertical);
	}

(because i’ve turned my object, up is forward, and forward is vertical, yesyes, silly me :P)

The problem with this is, my forward momentum gets almost nullified when im moving to the sides, because my velocity is exceeding the maximum allowed.

I have also tried moving the first line outside the if-sentence, but that will give me some jaggy movement when im trying to move to the sides, again, because my movement is limited by my maximum velocity.

So, im curious, is there an alternative to what im doing?, if im messing up here because i’ve missed something in the documentation, then please point me in the right way.

Thanks in advance.

Kacer

Edit: here’s the solution to my issue, on second thought it could probably have been done a bit simpler.

        if(rigidbody.velocity.z < maxforwardspeed)
			rigidbody.AddForce(transform.rotation * Vector3.up * 1);
		
		if(rigidbody.velocity.x > minspeed && rigidbody.velocity.x < maxspeed && rigidbody.velocity.y > minspeed && rigidbody.velocity.y < maxspeed){
			rigidbody.AddForce(transform.rotation * Vector3.right * horizontal);
			rigidbody.AddForce(transform.rotation * Vector3.forward * -vertical);
		}

You can try

rigidbody.AddForce(transform.rotation * Vector3.up * 1);
rigidbody.AddForce(transform.rotation * Vector3.right * horizontal);
rigidbody.AddForce(transform.rotation * Vector3.forward * -vertical);

if(Mathf.Abs(rigidbody.velocity.y)>maxspeed)
rigidbody.velocity.y=maxspeed;
if(Mathf.Abs(rigidbody.velocity.x)>maxspeed)
rigidbody.velocity.x=maxspeed;
if(Mathf.Abs(rigidbody.velocity.z)>maxspeed)
rigidbody.velocity.z=maxspeed;