# MRUA implementation optimization issues

I am implementing the MRUA formulas as an extension method in the rigidbody class, the main porpuse is to try and make the rigidbodys to move from pose A to pose B just using velocitys so i dont have problems with collisions. the code works fine it ismply calculates the time needed to stop the object, get the distance calculated in that time and compare if the distance from the player is lower than the distance to stop the object. but now i want to go a step forward, i am trying to create a coroutine method for moving the objects when both pose A and pose B are fixed, the code used in the other method for calculating each iteration when to start slowing down would work, but doesnt seem like the most efficient way of doing this. here is the code used as an example

``````    public static void MoveByForces(this Rigidbody body, Vector3 target, float maxSpeed, float acceleration, float deceleration, float offset = 0.0f)
{
float distance = Vector3.Distance(target, body.position);

if(distance <= offset)
{
body.velocity = Vector3.zero;
body.MovePosition(target);
return;
}

float currentVelocity;
float decelerationDistance = DistanceCalculation(body, deceleration, out currentVelocity);

if (distance < decelerationDistance)
{
currentVelocity -= deceleration;
}
else
{
if (currentVelocity < maxSpeed)
{
currentVelocity += acceleration;
}
}

body.velocity = (target - body.position).normalized * currentVelocity / Time.fixedDeltaTime;
}
``````

Your code has multiple problems.

First, if the target moves, the object will turn instantly at full speed. This might look jarring in an otherwise realistic movement.

Second, performance wise, `Distance`, `magnitude` and `normalized` are the biggest problem, as they involve a square root and three multiplications.

Without the DistanceCalculation I can only do so much, but here I reduced the amount of square roots from 2 to 1, and the amount of float multiplications from 12 to 9.

``````public static void MoveByForces(this Rigidbody body, Vector3 target, float maxSpeed, float acceleration, float deceleration, float offset = 0.0f)
{
float dir = target - body.position;
float distance = dir.magnitude;

if(distance <= offset)
{
body.velocity = Vector3.zero;
body.MovePosition(target);
return;
}

float currentVelocity;
float decelerationDistance = DistanceCalculation(body, deceleration, out currentVelocity);

if (distance < decelerationDistance)
{
currentVelocity -= deceleration;
}
else
{
if (currentVelocity < maxSpeed)
{
currentVelocity += acceleration;
}
}

body.velocity = dir * (currentVelocity / distance / Time.fixedDeltaTime);
}
``````