Positioning Screen Space UI element in center of a grid square?
I want to be able to click/touch anywhere in a grid square and snap a screen space UI element (popup menu) to the center of that square.
I have an empty gameobject that has a grid with each box equal to one world unit (see screenshot bellow). The gameobject has a transform, a box collider, and script on it. I can snap to a local position in the grid with the code below, but I can’t seem to figure out how to convert a Local point to Screen Space point. How can I find the coordinates to snap a Screen Space UI element to the center of a grid square that is in local world units?
Thanks for the help
< TL;DR >
This code works for locally positioned gameobject, how do I get from here to screen space UI element snapped to the center of a grid square?
// Snaps a local positioned gameobject to the center of a grid square.
// Each grid square is one world unit.
// midPoint = 0.5f;
transform.position = new Vector3(Mathf.FloorToInt(localPoint.x) + midPoint, Mathf.FloorToInt(localPoint.y) + midPoint, localPoint.z);
Screenshot of the prototype with grid.
Answer by toothytoad · Apr 11, 2017 at 06:23 PM
I figured it out something that works.
_localPoint = new Vector3(Mathf.FloorToInt(localPoint.x) + midPoint, Mathf.FloorToInt(localPoint.y) + midPoint, localPoint.z);
_menu.transform.position = ConvertLocalToScreenPoint(_localPoint);
// ...
private Vector3 ConvertLocalToScreenPoint(Vector3 localPoint)
{
return RectTransformUtility.WorldToScreenPoint(Camera.main, transform.TransformPoint(localPoint));
}
Your answer
Follow this Question
Related Questions
How to make rotating objects with snapping to grid while the object contains children 0 Answers
Locate a free-moving 2D object's position in a grid. 1 Answer
RedctTransform messed up after moving UI components around 0 Answers
How to get vector3 grid position for object dynamically 1 Answer
Snap object to the local grid. 1 Answer