- Home /
Clamping velocity and angular velocity at the same time?
I have a 2D ball (with rigidbody2D) on a surface and I can roll it by using AddForce(). However I want it to rotate at the sametime therefore I rotate it using AddTorque(). This works very nice but...
1) I want to set an upper limit for the speed. I cannot find a way to clamp both velocity and angular velocity precisely. 2) I want to stop the torque immediately when the ball hits something (just like a real physical ball).
The following is my code:
//press left or right to roll the ball
rigidbody2d.AddForce (new Vector2(Input.GetAxis ("Horizontal") * speed, 0));
rigidbody2d.AddTorque (-Input.GetAxis ("Horizontal") * speed);
//don't roll too fast
rigidbody2d.velocity = new Vector2 (
Mathf.Clamp(rigidbody2d.velocity.x, -maxVelocity, maxVelocity),
rigidbody2d.velocity.y);
I've tried recording the angular velocity when the linear velocity reaches its maximum, however the number becomes imprecise after a while (probably because of rounding numbers).
Comment