Lead foot... Acceleration too high

Hi, all,

I am using the following script to accelerate my player object. It works very well, except I would like to dial back the top speed which is too fast. The drag var only seems to slow the object once the button is off. Could anyone point me to the solution?

Thanks,

Greg

var target : Rigidbody;
var pedalImage : Texture2D;
var acceleration : float = 20;
var drag : float = 1.0;

private var accelerate : boolean = false;


function FixedUpdate()
{
   if (accelerate)
   {
      target.drag = 0;
      target.AddRelativeForce(0,0,acceleration);
   }
   else
   {
      target.drag = drag;
   }
}
function OnGUI()
{
   if (GUI.RepeatButton (Rect (380,220,100,100), pedalImage))
   {
      accelerate = true;
   }
   else
   {
      accelerate = false;
   }

A simple way is to check the velocity’s magnitude, and if it’s over the limit, don’t add the force. A somewhat better way is to add less and less force the closer the velocity is to the max. I’m not sure that you actually want to remove drag when accelerating though.

–Eric

Thanks, Eric,
Would you recommend using the following line to check magnitude?

if (transform.position.magnitude <1.0){

It’s rigidbody.velocity.magnitude.

–Eric

It’s a good idea to throw in some Mathf.Clamp statements, preferably applied directly to the velocity values.
They say to try not to set the velocity directly, but putting in clamps right at the end for a sanity check seems pretty safe and can save you from unexpected weirdness.

Thanks, guys. I’ve cobbled something together that I may need some advice on in the future. I appreciate your time.