Swimer
Swimer

Reputation: 61

How do I get the coordinates of the mouse relative to the world?

How to get the position of the mouse in the scene I use:

Vector2 screenPosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
Vector2 worldPosition = Camera.main.ScreenToWorldPoint(screenPosition);
Debug.Log(worldPosition);

I click on an object whose coordinates are "56.1 98" And the result of the code: (6.9, 55.2) Why is that? And how to do it normally?

Unity version: 2020.3.15f2

Upvotes: 0

Views: 98

Answers (1)

yasirkula
yasirkula

Reputation: 711

ScreenToWorldPoint accepts a Vector3 and that Vector3's z component determines the distance of the returned point from the camera. In your case, you don't know the distance between the camera and the clicked object's surface. So you must use Raycast instead:

Ray ray = Camera.main.ScreenPointToRay( screenPosition );
if( Physics.Raycast( ray, out RaycastHit hit ) ) // Check if we've clicked on an object with Collider
{
    Vector3 clickedSurfacePosition = hit.point; 
    Debug.Log( clickedSurfacePosition );

    Vector3 clickedObjectTransformPosition = hit.transform.position;
    Debug.Log( clickedObjectTransformPosition );
}

If you're working with 2D physics:

RaycastHit2D hit = Physics2D.GetRayIntersection( Camera.main.ScreenPointToRay( screenPosition ) );
if( hit ) // Check if we've clicked on an object with Collider2D
{
    Vector2 clickedSurfacePosition = hit.point;
    Debug.Log( clickedSurfacePosition );

    Vector3 clickedObjectTransformPosition = hit.transform.position;
    Debug.Log( clickedObjectTransformPosition );
}

Upvotes: 1

Related Questions