Hello, I'm trying to clamp the velocity of a Rigidbody, as you can see in the code below. As far as I can tell, the process I'm using should be correct, also because the debug log outputs the right value. Visually tho, when I change the acceleration value, the Rigidbody not only accelerates faster (as it should happen) but it also seems to move faster (through the debug.log still tells me that the velocity vector is clamped)... Any Idea why? Code (CSharp): private void FixedUpdate() { Vector3 direction = new Vector3(input.x, 0f, input.y); playerRigidbody.AddForce(direction * acceleration, ForceMode.VelocityChange); if (playerRigidbody.velocity.magnitude > maxSpeed) playerRigidbody.velocity = Vector3.ClampMagnitude(playerRigidbody.velocity, maxSpeed); Debug.Log(playerRigidbody.velocity.magnitude); }
I think you're missing something in your conditional statement. Code (CSharp): if (playerRigidbody.magnitude > maxSpeed) I think it should be Code (CSharp): if (playerRigidbody.velocity.magnitude > maxSpeed)
It was a typo, I cpoied my code and removed the comments to have it take less space in my post and somehow deleted that part as well. Now the code is exactly as I have it, and the outcome is still as described :S
Adding a force in 3D physics doesn't actually happen until the simulation step. The velocity before and after you're adding force will be the same. You're better off directly manipulating the velocity here like so: Code (CSharp): private void FixedUpdate() { var force = new Vector3(input.x, 0f, input.y) * acceleration; var velocity = playerRigidbody.velocity + force; playerRigidbody.velocity = Vector3.ClampMagnitude(velocity, maxSpeed); }