How can I delay object mouse following?

So I’m trying to make a game like Space Invaders, but with mouse control, and I’m stuck. I’m trying to make the main object follow my mouse with some delay to prevent it from following the mouse instantly so I made this script:

using UnityEngine;

public class Player : MonoBehaviour {
    private InputReader inputReader;
    private Rigidbody2D Rb2D;

    private void Awake() {
        inputReader = GetComponent<InputReader>();
        Rb2D = GetComponent<Rigidbody2D>();
    }
    private void Update() {
        Vector3 mousePos = UtilisClass.GetMouseWorldPosition();
        Vector3 target = (mousePos - transform.position).normalized;
        Rb2D.velocity = target;
    }
}

Now it works perfectly, but the main problem is that when the object reaches the mouse position, it starts randomly vibrating/bouncing. I tried to solve it by checking the magnitude and set the velocity to 0, but that made the movement laggy and weird when the object close to the mouse position. I would be happy for any suggestions on how to solve this problem! Thanks in advance :slight_smile:

Thank you very much for the quick reply! I tried it, and it worked. However, there is one issue: the ship becomes slower when it gets closer to the mouse point but I will try to fix it by myself.
Thank you very much for pointing me! :slight_smile:

Smoothing movement between any two particular values:

You have currentQuantity and desiredQuantity.

  • only set desiredQuantity
  • the code always moves currentQuantity towards desiredQuantity
  • read currentQuantity for the smoothed value

Works for floats, Vectors, Colors, Quaternions, anything continuous or lerp-able.

The code: SmoothMovement.cs · GitHub

Thank you very much! I used it in my code, and it works perfectly. Thank you! :)))

Edit: Thanks to Kurt-Dekker, I managed to find a solution:

public class Player : MonoBehaviour { 
    private Rigidbody2D Rb2D;
    private Vector2 currentPos;
    private Vector2 targetPos;
    private float MovementPerSecond = 10.0f;

    private void Awake() {
        Rb2D = GetComponent<Rigidbody2D>();
    }
    private void Update() {
        Debug.Log(currentPos);
        Rb2D.MovePosition(ProcessMovement());
    }
    private Vector2 ProcessMovement() {
        targetPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        currentPos = Vector2.MoveTowards(currentPos,
            targetPos,
            MovementPerSecond * Time.deltaTime);
        return currentPos;
    }
}