How to move an object with a selected speed to the mouse?

How can I move an object to the mouse with a specific speed? I mean like it moves towards the mouse with (20px/s) and its not matter how far the mouse is. My code is: KohlsFeedback.com

public class PlayerMovement : MonoBehaviour
{
    private Vector3 mousePosition;
    public float moveSpeed = 0.02f;
    
    void Update()
    {
        mousePosition = Input.mousePosition;
        mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
        mousePosition.z += Camera.main.nearClipPlane;
        transform.position = Vector2.Lerp(transform.position, mousePosition, moveSpeed * Time.deltaTime);
    }
}

Because using this (This is the only code I found online) if the mouse is far away the object move faster.

-Thanks!

Hi!

The reason the speed changes with bigger distances is that in your current code, the next position is always some percentage between the two points instead of some distance toward it.

You can try using Vector2.MoveTowards(). That should be what you’re looking for.

Docs: Unity - Scripting API: Vector2.MoveTowards

Hope this helps!