- Home /
Rigidbody character, normalize diagonal speed without limiting external rb.addforces?
Hi! I know normalizing the diagonal velocity is the popular method of fixing faster diagonal speed, but that also means my character cannot go faster than that even from external forces, for example if an explosion happened, the character wouldn't be able to launch away at a faster speed. I have a rigidbody character in Unity3D that I use rb.addforces to control. To limit it's speed I basically zero out my input if my velocity is greater than the maxSpeed.
I know I can probably increase the maxSpeed in events like explosions and dashes etc but is there a solution around this? Becus changing the maxSpeed for every event in the future might be a hassle.
Here's a snippet of my player movement code (without any normalizing):
void Move() {
float x = Input.GetAxisRaw("Horizontal");
float z = Input.GetAxisRaw("Vertical");
//vel relative to look direction
float xVel = vel.x;
float zVel = vel.y;
//no input if exceeding max speed
if (x > 0 && xVel > maxSpeed) x = 0;
if (x < 0 && xVel < -maxSpeed) x = 0;
if (z > 0 && zVel > maxSpeed) z = 0;
if (z < 0 && zVel < -maxSpeed) z = 0;
// normalize diagonal speed and remove input if sliding
Vector2 flatVel = new Vector2(rb.velocity.x, rb.velocity.z);
if (Mathf.Abs(flatVel.magnitude) > maxSpeed || isSliding) {
x = 0;
z = 0;
}
CounterMovement(x, z);
//move forward and sideways
rb.AddForce(transform.forward * z * moveSpeed);
rb.AddForce(transform.right * x * moveSpeed);
//change direction of player faster
if (zVel > 0.2f && z < 0) rb.AddForce(-transform.forward * turnSpeed);
if (zVel < -0.2f && z > 0) rb.AddForce(transform.forward * turnSpeed);
if (xVel > 0.2f && x < 0) rb.AddForce(-transform.right * turnSpeed);
if (xVel < -0.2f && x > 0) rb.AddForce(transform.right * turnSpeed);
// //max speed check
// Vector2 flatVel = new Vector2(rb.velocity.x, rb.velocity.z);
// if (flatVel.magnitude > maxSpeed) {
// flatVel = flatVel.normalized * maxSpeed;
// rb.velocity = new Vector3(flatVel.x, rb.velocity.y, flatVel.y);
// }
}
Your answer
Follow this Question
Related Questions
Rigidbody movement script 2 Answers
Rigidbody causes ragdoll character to fly 4 Answers
How to make a rigidbody move in the direction of finger(x,y,z) 1 Answer
Child object not moving with parent 3 Answers