GameObject jitter at endPosition

public class InputController : MonoBehaviour
{
bool loadMainMenu = false;
public float speed = 1.5f;
private Vector3 _target;
private Vector3 _dir;
private Rigidbody2D _rb;

    // Use this for initialization
    void Start()
    {
        _target = transform.position;
        _rb = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate()
    {
        Debug.Log(_target);

        _dir = (_target - transform.position).normalized * speed;
        _rb.velocity = _dir;
        Debug.Log(transform.position);
    }
    void LateUpdate()
    {
        if (Input.GetMouseButtonDown(0))
        {
            _target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            _target.z = transform.position.z;
        }
    }
}

}

I attached this script to a Player and the movements are responding to the mouse clicks smoothly. However, once the player ends up at the clicked position, it starts to jitter. I’ve tried interpolation, it only put the jitter in slow-mo lol.

The player has a rigidbody and collider attached to it. This game is a 2D game.

Well you will never exactly reach your target. Each physics frame you just move “towards” the target point if you are already very close to the target you will “overshoot” the target. The next frame the direction will point in the opposite direction since you’re now on the other side and you will move backwards. So your object oscillates around the target. You should detect if you reached the target and set the position to the target if you’re close enough to the target.

void FixedUpdate()
{
    var dir = _target - transform.position;
    var dist = dir.magnitude;
    if (dist < speed * Time.fixedDeltaTime)
    {
        _rb.MovePosition(_target);
        dir = Vector3.zero;
    }
    else
        dir /= dist; // normalize "dir"
    _rb.velocity = dir * speed;
}

This will check the distance to the target and if it’s too close (smaller than the distance it would travel in one physics frame) it simply puts the object at the target position and sets the direction to (0,0,0). Since we have already calculated the length of the “dir” vector we can manually normalize it to save the additional square root ^^.