Accelerate a rigidbody towards max speed

Hey guys,

I’m currently in the process of creating a naval game, and I have been trying to find a way for the ships (which have rigidbodies) to accelerate or decelerate to a certain speed. Drag will affect the ships. Any ideas on how I would approach this problem?


(By the way, I am aiming for movement similar to that of World of Warships.)

It’s called a PID loop, though you’ll only be implementing the “D” (derivative) part of it. You compute a Vector3 that is the target velocity (how fast you want the ship to go). Subtract the ship’s actual velocity from it, and multiply by a constant to get a force. The force will be high when the ship is far from the target velocity, and zero when the two match.

Vector3 targetVelocity = transform.rotation * Vector3.forward * targetSpeed;
Vector3 force = (targetVelocity - rb.velocity) * forceMult;

Edit - Since you’re modeling ships, you might want to clamp the force so that it doesn’t exceed the maximum thrust of the ship.

if (force.magnitude > forceMax)
    force = force.normalized * forceMax;

Since it seems you use drag, have a look at my answer over here

You may want to use the “GetRequiredAcceleraton” method. Keep in mind that the required force is just the required acceleration multiplied by the object’s mass. Though you can simply use ForceMode.Acceleration. When using ForceMode.Force Unity simply divides the incoming force by the mass to determine the acceleration internally.