3
\$\begingroup\$

I am trying to gradually accelerate a GameObject with a RigidBody attached until it reaches a maximum velocity, at which point it becomes unable to gain any more velocity.

  • I know I can simply reset the object velocity to an arbitrary maximum velocity every frame if it overshoots, but I've repeteadly heard that manually setting an object's velocity is a very bad practice in the context of Unity's physics system.
  • I am also aware that in a physical sense, objects don't have a "maximum velocity" and that such a thing will always be artificial.

I can think of several ways to achieve this, but given these limitations, I would like to know if there's a standard, optimum way to do this.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ "I've repeatedly heard that manually setting an object's velocity is a very bad practice" There's a lot of questionable Unity advice out there. ;) Setting the velocity isn't universally bad, you just need to be a bit careful about how you do it, to make sure it's not overriding some other behaviour you want, like a velocity effect from another script, or a collision response. If you only ever reduce the velocity while keeping its direction, it should be safe for most contexts. \$\endgroup\$
    – DMGregory
    Jan 22, 2018 at 0:01

1 Answer 1

3
\$\begingroup\$

What you want to do is not to set the max velocity, but void applying any additional force once you get to a certain speed. Something like the example below. Watch the if statement

public float force;
public float sqrMaxVelocity;

private Rigidbody rg;

void Start()
{
    rg = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    if (Input.GetKey(KeyCode.UpArrow) && rg.velocity.sqrMagnitude < sqrMaxVelocity)
    {
        rg.AddRelativeForce(Vector3.up * force ,ForceMode.Force);
    }

}
\$\endgroup\$
3
  • \$\begingroup\$ Good, but I would instead check rg.velocity.sqrMagnitude < sqrMaxVelocity to avoid an unnecessary sqrt calculation \$\endgroup\$
    – Ed Marty
    Jan 22, 2018 at 16:30
  • \$\begingroup\$ @EdMarty Very true. I just checked the unity manual and indeed sqrMagnitude is much faster. "Calculating the squared magnitude instead of using the magnitude property is much faster - the calculation is basically the same only without the slow Sqrt call" \$\endgroup\$
    – Fabio S.
    Jan 22, 2018 at 16:50
  • \$\begingroup\$ Check out this answer's AccelerateTo method for an example of how to accelerate up to a target speed without going all-or-nothing. You can gradually taper off your acceleration as you approach the limit so that you reach, but don't overshoot, your target. This can give a smoother resulting motion. \$\endgroup\$
    – DMGregory
    Jan 22, 2018 at 18:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .