- Home /
ScreenToWorldPoint for different resolutions in 2D
Hello. I'm developing a 2D game and I need to be able to detect the mouse position in the game world. The thing is, when I'm on the editor it works just fine, but when I run the standalone and set a resolution when an aspect ratio different than the native one it has a weird offset.
The red dot represents the mouse position and the white line should go from the center of the character (it is correct) to the mouse pointer. As you can see, it has an offset in the X axis.
The code that does the work is the following.
GameObject useHook(Vector3 mousePosition)
{
Vector2 ray2D = Camera.main.ScreenToWorldPoint(mousePosition);
RaycastHit2D hit = Physics2D.Raycast(ray2D, Vector2.zero);
if (hit.collider != null)
{
GameObject target = hit.collider.gameObject;
if (target.tag.Equals("Grappleable"))
{
grapplingHook.enabled = true;
hookDrawing.enabled = true;
hookDrawing.SetPosition(1, ray2D);
grapplingHook.connectedAnchor = ray2D;
if (target.transform.Find("ContactPoint") != null)
{
target.transform.Find("ContactPoint").position = ray2D;
grapplingHook.connectedAnchor = target.transform.Find("ContactPoint").position;
return target.transform.Find("ContactPoint").gameObject;
}
return null;
}
return null;
}
return null;
}
offset.png
(20.1 kB)
Comment
Take a look to the asset 2D Ninja Rope. In scene 2 ist exactly what you want to do: