unit – Accelerate / slow down to a moving target and hit it

I'm trying to create a fluid camera movement in 2D. The target I want to reach can potentially travel a great distance in a single image and does not look like a character moving smoothly from A to B.

I am aware of possible solutions like using Vector2.Lerp ()but this approach only slows down, but accelerates sharply.

_position = Vector2.Lerp (_position, target, 0.5f * Time.deltaTime);

I've tried to implement the "arrival" direction behavior, but I can not make it work properly with acceleration, especially when the target is close to the current position.

I managed to make it work pretty well in one axis, but this approach did not work when it was repeated in a second axis.

var decelerateRadius = GetDistanceFromAcceleration (acceleration, Mathf.Abs (_velocity));
var direction = target - _position;
var distance = Mathf.Abs (direction);
var a = acceleration * Time.deltaTime;

if (distance> 0.0005f)
{
if (distance < decelerateRadius.x)
    {
        _velocity *= distance / decelerateRadius.x;
    }
    else
    {
        _velocity += direction.x >= 0.0f? a: -a;
}
}
other
{
_velocity = 0.0f;
}

// move the tracker
_position + = _velocity * Time.deltaTime;

And my method to calculate the distance according to the acceleration:

private Vector2 GetDistanceFromAcceleration (float a, float vx, float vy)
{
// derived from: a = (vf ^ 2 - vi ^ 2) / (2 * d)
returns the new vector2 (vx * vx / (2.0f * a), vy * vy / (2.0f * a));
}

My last attempt was to get a moving average of the target, but the problem was the same as lerping.

To summarize the requirements:

  • Must accelerate
  • Must decelerate and stop at the target
  • Must not "orbit" or otherwise turn around the target before stopping
  • Target must be able to move
  • Can be limited by a maximum speed

Advice, suggestions and solutions to achieve it?


I've also asked the question on stackoverflow: https://stackoverflow.com/questions/55691355/accelerate-decelerate-towards-moving-target-and-hitting-it