Constraint an object speed
Hello,
I don't want my ball goes at a greater speed as I set in "AddForce()".
Is this code correct ?
void Update()
{
if (ball.GetComponent<Rigidbody>().velocity.magnitude > 250.0f)
{
ball.GetComponent<Rigidbody>().SetMaxAngularVelocity(250.0f);
}
}
void Update()
{
if (ball.GetComponent<Rigidbody>().velocity > maxVelocity)
{
ball.GetComponent<Rigidbody>().velocity = maxVelocity;
}
}
Answer by LK84 · Jan 11, 2017 at 09:39 AM
SetMaxAngularVelocity only constraints the rotational velocity. I assume you want to constraint the translational velocity since you state this in your if-condition? And: Put in in the FixedUpdate() loop!
To constrain the translational velocity you got two options:
The non-physics way (I don't recommend because you gonna mess with the physics engine)
The physics way which probably takes a little more time to get exactly what you want
For (1) You could write something like this:
const float maxSpeed=250;
void Start()
{
rigidbody=GetComponent<Rigidbody>();
}
void FixedUpdate()
{
if(rigidbody.velocity.magnitude > maxSpeed)
{
rigidbody.velocity = rigidbody.velocity.normalized * maxSpeed;
}
}
For (2) you can either experiment with the drag value of your rigidbody in the inspector or write your own function, something like this:
rigidbody.AddForce(-rigidbody.velocity*dampC); //dampfC is a damping Coefficient you can define yourself
ok, but be careful using it. It's not the "physical correct way" to do it.
Answer by tanoshimi · Jan 11, 2017 at 09:37 AM
You're muddling up velocity (position) with angularVelocity (rotation). Also you don't need to keep setting a maximum value every frame - you can just set it once and it will persist. You should also try to avoid using GetComponent in Update - it's expensive. Find the rigidbody once in Start and re-use the result from them on.
Try this instead:
private Rigidbody rb;
void Start() {
rb = ball.GetComponent<Rigidbody>();
}
void Update()
{
if (rb.velocity.magnitude > 250.0f)
{
rb.velocity = rb.velocity.normalized * 250f;
}
}
Your answer
Follow this Question
Related Questions
Best ads for mobile game? 1 Answer
Sphere with AddForce or Velocity not moving 1 Answer
Addforce is not working 1 Answer
2d add force inconsistency 0 Answers
Physics-related touch input (Continuous) 0 Answers