Answers for "(C#) Accelerating Player Based On Distance"
http://answers.unity.com/questions/1576258/c-accelerating-player-based-on-distance.html
The latest answers for the question "(C#) Accelerating Player Based On Distance"Answer by 1337keegan
http://answers.unity.com/answers/1576445/view.html
That's excellent, thank you! However is there a way to do this positionally rather than through force? my object isn't a rigidbody, it's a 2D sprite and I would like to manipulate it through transform.position if at all possible.Fri, 30 Nov 2018 16:37:34 GMT1337keeganAnswer by Eno-Khaon
http://answers.unity.com/answers/1576358/view.html
This is where a <b>[good reference point][1]</b> can really come in handy.
<br> <br>
By a typical acceleration formula, you're taking the <i>current speed</i>, the <i>target speed</i>, and the time spent accelerating between those two speeds. With that information, you can determine the distance traveled and the rate of acceleration to reach that point.
<br> <br>
This is done using the formulas:
> <sup>tgtSpeed-curSpeed</sup>/<sub>time</sub> = acceleration
>
> (<sup>avgSpeed</sup>/<sub>2</sub>)*time = distance
<br>
Since you know the distance, however, let's take this equation and work backwards, shall we?
> <sup>distance</sup>/<sub>avgSpeed</sub> = time
<hr>
<b>Yep, time still winds up being a valuable factor in this.</b> But since the time can be determined by reversing the <i>speed-to-distance</i> equation, you can use that to turn it back around and calculate the acceleration rate (force) to apply to reach the desired speed.
public static float AccelerateToTarget(float currentSpeed, float targetSpeed, float distance)
{
float averageSpeed = (currentSpeed + targetSpeed) * 0.5f;
float time = distance / averageSpeed;
float speedDifference = targetSpeed - currentSpeed;
float acceleration = speedDifference / time;
return acceleration;
}
float forceToAdd;
void Start()
{
Rigidbody rb = GetComponent<Rigidbody>();
// Example call using your values
forceToAdd = AccelerateToTarget(rb.velocity.magnitude, 3.0f, 0.5f);
}
void FixedUpdate()
{
rb.AddForce(transform.forward * forceToAdd);
}
<br>
Granted, this example won't stop accelerating after it reaches that speed after that time, but it will reach the target speed of 3u/s upon traveling 0.5 units <i>(not counting applicable approximation errors and friction)</i>.
[1]: https://www.omnicalculator.com/physics/accelerationFri, 30 Nov 2018 10:54:44 GMTEno-Khaon