- Home /
Position auto-scaled UI element with Camera.WorldToScreenPoint
I've got a Canvas
. I'm creating some Text
elements right above 3D objects in the scene with this code:
Vector3 screenPos = Camera.main.WorldToScreenPoint(this.dices[x, z].transform.position);
screenPos.x -= 25;
screenPos.y += 10;
newScoreItem.GetComponent<RectTransform>().anchoredPosition = screenPos;
On Android my UI elements are tiny so I set the surrounding Canvas` UI Scale Mode to "Scale with screen size".
The problem is that the position I determine with the code above doesn't match the one of scaled canvas. My Text
elements are scaled but at the completely wrong location.
How may I solve that problem?
Answer by yoziva · May 22, 2015 at 07:07 PM
This should work :
public static Vector3 GetScreenPosition(Vector3 position, Canvas canvas, Camera cam)
{
var size = canvas.GetComponent<RectTransform>().sizeDelta;
var screenPos = cam.WorldToScreenPoint(position);
var x = (screenPos.x / Screen.width) * size.x * canvas.transform.localScale.x;
var y = (screenPos.y / Screen.height) * size.y * canvas.transform.localScale.y;
return new Vector3(x, y);
}
Answer by shmidtke · Mar 18, 2016 at 04:46 PM
The easiest way I've found: %|-410303890_1|% %|-1967193984_2|% screenPos.y *= MainCanvas.sizeDelta.y;
where MainCanvas - root RectTransform;
Your answer
Follow this Question
Related Questions
UI RectTransform Position && Screen Resolution 2 Answers
spawn UI elements on top of other gameObjects 2 Answers
How to change the gameobjects position and transform in a scene when the device orientation changes. 1 Answer
Camera rotation around player while following. 6 Answers
How to set the UI Text position to be relative to his "grandfather" prefab 0 Answers