How to accelerate an object by time, rather than max delta

So my question is this: Say I want my object to accelerate to the requested speed in 5 seconds. How would I go about doing this?

This is my current code:

[In fixed update]

move = new Vector3(Mathf.MoveTowards(move.x, speed * input.x, accel), input.y * (Mathf.Sqrt(5f * 9.81f) - 0.5f), Mathf.MoveTowards(move.z, speed * input.z, accel));

The move vector is the speed to change the rigidbody, and the input vector is a vector based on input. [input.x is 1 when W is pressed, -1 when S, and so on]

That line of code looks very odd…

  • MoveTowards expects a current position, a target position, and a delta, but you’re passing a current position (in components) a speed, and a constant.
  • I don’t see anything to make this framerate independent (i.e. no Time.deltatTime, Time.fixedDeltaTime).
  • Why is this is FixedUpdate rather than Update?
  • DON’T do a sqrt of constants each frame!
  • What changes accel? I’d expect it to be linked to input, but that’s not the case.

I think this is closer to what you’re trying to do:

Vector3 speed; // Object's speed in x,y,z
Vector3 input; // Player input in x,z,y
Vector3 accel = new Vector3(1f,1f,Mathf.Sqrt(5f*9.81f)-0.5f)); // The rate of change in x,y,z

Update() {
  speed += input * accel; // Apply acceleration to current speed
  move += speed * Time.deltaTime; // Apply speed to position, per second
}

You could try something different and simply assign a value that corresponds to your object’s max speed in units/sec. Like:

rigidbody.velocity = transform.forward * power;

Now you can use Lerp to change that value over time.

function ChangeSpeed(newPower : float, time : float)
 {
     var elapsedTime : float = 0;
     var startingPower : float = power;
     while (elapsedTime < time)
     {
         power = Mathf.Lerp(startingPower, newPower, (elapsedTime / time));
         elapsedTime += Time.deltaTime;
         yield;
     }

 }

Then you simply call the ChangeSpeed method once and feed it your target speed and duration.

//sim-ish throttle controls

If (Input.GetKeyDown(KeyCode.Alpha1)) {
     //speed changes from current to 10 in 5 seconds
     ChangeSpeed(10,5);
     }

If (Input.GetKeyDown(KeyCode.Alpha2)) {
     //speed changes from current to 20 in 5 seconds
     ChangeSpeed(20,5);
     }

If (Input.GetKeyDown(KeyCode.Alpha3)) {
     //speed changes from current to 30 in 5 seconds
     ChangeSpeed(30,5);
     }

Source:
link text

The answer is the kinematic equations. Any high school physics text book can provide you with a chapter explaining it. Google found this one pretty quick