- Home /
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);
}
Answer by yeoldesnake 1 · Sep 27, 2011 at 02:37 PM
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;
This would not work, for the same reasons as above, your script will limit the total magnitude, which means, that if i max out my speed on the z axis, then i wont be able to move on the x and y axis.
also because rigidbody.velocity.magnitude is read only :)
Thought so , then why not limit rigidbody.velocity.y , rigidbody.velocity.x and rigidbody.velocity.z
Hmm, that works, though, i have to write some extra code, i'll write what i've written as an edit in my original post.
well, your edit wont work, as you cant edit those values directly, plus you're not taking into account that when you're moving to the left you have a negative value as your velocity.