How to find the mouse position in 2d?

I know its probably very simple but I have no clue how. I want to set an object so it follows the mouse position but I tried using input.mousePosition but I don’t want it to follow my mouse only when I click. Any help would be appreciated

1 Like

The mouse is in screenspace, where (0,0) is the bottom-left of the screen. Transform.position, in contrast, uses worldspace. We need to convert between the two coordinate systems like so:

    var mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    mouseWorldPos.z = 0f; // zero z

Typically it’s worthwhile to zero the z b/c it’s a 2D game and it’ll be populated with a useless value.

How to follow when leftmouse is pressed down?

if(Input.GetMouseButton(0))
{
    var mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    mouseWorldPos.z = 0f; // zero z
    transform.position = mouseWorldPos;
}

A GameObject with this logic in its Update() will move to the mouse’s worldspace position when the mouse is held down.

You might also want to detect specifically which object (of several) was clicked. If you put a Collider2D on that object you can then make use of the OnMouse hooks. See the “OnMouse…” options here: Unity - Scripting API: MonoBehaviour

Using that hook might look like this:

void OnMouseDrag()
{
    var mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    mouseWorldPos.z = 0f; // zero z
    transform.position = mouseWorldPos;
}

This does the same as using Update(), but only to the dragged object.

9 Likes