When we want to make a on screen marker to identify the shooting target on screen.
basically we asking “how to convert World position into UGUI screen position in term of RectTransform anchor.”
Technically speaking it’s a space convert issue.
in this case assume we following Object in the scene :
- m_WorldPosition : the target position we wanted to display but in 3D world space (perhaps the raycast hit point?!)
- m_ViewCamera : a camera for player to explore virtual world. (upper camera)
- m_UICamera : a camera only culling UI overlayer (camera only for UI)
- m_MarkerRect : the RectTransform based on UGUI Canvas. (the MARKER)
so here is what we wanted to do :
- first we need to convert the world position (m_WorldPosition) from “m_ViewCamera” into the screen position
- and then use that screen position based on “m_UICamera” matrix, convert onto UGUI RectTransform anchorPosition
so the code will look like this.
// assume we had following // RectTransform m_MarkerRect; // Camera m_ViewCamera; // Camera m_UICamera; // Vector3 m_WorldPosition; Vector3 screenPos = m_ViewCamera.WorldToScreenPoint(m_WorldPosition); bool withInParentRect = RectTransformUtility.ScreenPointToLocalPointInRectangle((RectTransform)m_MarkerRect.parent, screenPos, m_UICamera, out Vector2 anchorPos);
we used following API.
Notes: by using the “RectTransform.anchoredPosition” we can define the center of the image or what ever you wanted for the UI’s pivot poition.