- Home /
Question by
lirizstudios · May 23, 2019 at 02:19 PM ·
c#rigidbody2drigidbody.velocity
how can I set a limit to the speed of the rigidbody2d in Unity ??
I want the velocity parameter in 'x' not to exceed the maximum amount (Example (5, 0) maximum)
capture.png
(13.7 kB)
Comment
Answer by Jack-Mariani · May 23, 2019 at 02:29 PM
You can easily implement this functionality with a script.
public class RBSpeedLimit : MonoBehaviour
{
private Rigidbody2D rb2D;
public float maxHorizontalSpeed = 5;
public float maxVerticalSpeed = 5;
void Start() => rb2D = GetComponent<Rigidbody2D>();
private void FixedUpdate()
{
var velocity = rb2D.velocity;
//horizontal
if (velocity.x > maxHorizontalSpeed) velocity.x = maxHorizontalSpeed;
if (velocity.x < -maxHorizontalSpeed) velocity.x = -maxHorizontalSpeed;
//vertical, if required
if (velocity.y > maxVerticalSpeed) velocity.y = maxVerticalSpeed;
if (velocity.y < -maxVerticalSpeed) velocity.y = -maxVerticalSpeed;
rb2D.velocity = velocity;
}
}
Your answer