Put shooting marker on screen.

Put shooting marker on screen.

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 :

  1. m_WorldPosition : the target position we wanted to display but in 3D world space (perhaps the raycast hit point?!)
  2. m_ViewCamera : a camera for player to explore virtual world. (upper camera)
  3. m_UICamera : a camera only culling UI overlayer (camera only for UI)
  4. m_MarkerRect : the RectTransform based on UGUI Canvas. (the MARKER)

so here is what we wanted to do :

  1. first we need to convert the world position (m_WorldPosition) from “m_ViewCamera” into the screen position
  2. 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.

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

*

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料