- Home /
Canvas to World Coordinates Works in Editor but Not in Builds
Hi I have a cursor over some sprite objects, that cursor is part of the UI canvas, when the user presses the arrow keys the selector will move to another object in world space.
I use this code to calculate where the cursor should go.
public static Vector2 WorldToCanvasSpace(this Canvas canvas, Vector3 worldPosition)
{
Vector2 viewportPosition = Camera.main.WorldToViewportPoint(worldPosition);
return new Vector2((viewportPosition.x * Screen.width) - (Screen.width / 2),
(viewportPosition.y * Screen.height) - (Screen.height / 2));
}
My function works in the editor, it places the cursor at the correct "worldPosition" that I pass, but when I build the game the cursor is not in the correct position.
*When I say cursor I don't mean the mouse cursor.. just to be clear.
Any help would be delightful, thanks in advance.
Answer by ARKMs · Mar 03, 2017 at 02:35 AM
Try:
Vector3 viewport_position = Camera.main.WorldToViewportPoint(worldPosition);
RectTransform canvas_rect = canvas.GetComponent<RectTransform>();
return new Vector2((viewport_position.x * canvas_rect.sizeDelta.x) - (canvas_rect.sizeDelta.x * 0.5f), (viewport_position.y * canvas_rect.sizeDelta.y) - (canvas_rect.sizeDelta.y * 0.5f));
and set it to anchoredPosition.
Your answer
Follow this Question
Related Questions
Scalewithscreensize equivalent for worldspace canvas's 0 Answers
How to stop collider from interfering with world space canvas? 1 Answer
World Space not displaying my UI. Any suggestions? 2 Answers
Convert UI element to world position 1 Answer
UI canvas attached to vive controller disappears after first run in editor on vive 0 Answers