Better way to convert world space to uGUI canvas space?

I figured it out, but it’s kind of messy – is there an easier way?

The parent RectTransform needs to be set to stretchXY and the RectTransform that follows the world object needs to be set to bottom left anchor (to match orientation of screen space).

The CanvasScaler was throwing it off (set to Scale with screen size, matching height – if different, you might need a different solution), so I had to compensate. I couldn’t find a ‘current scale’ variable in CanvasScaler, so that’s what the scaleFactor variables are.

Vector3 screenPos = Camera.main.WorldToScreenPoint(target.Position);

float scaleFactorX = canvasScaler.referenceResolution.x / Screen.width;
float scaleFactorY = canvasScaler.referenceResolution.y / Screen.height;

myRectTransform.anchoredPosition = newVector2(screenPos.x * scaleFactorX, screenPos.y * scaleFactorY);

I tried searching, but I couldn’t find any examples – is there a simpler way to do this?

2 Likes

Thanks a lot for sharing :slight_smile: That works so fine they should add a function to the camera to do this as a shortcut, or at least add this to the documentation.
I banged my had for 3 days without getting better result but thanks to you it works fine now.

Edit:
I found another approach

3 Likes