Skip to content

Instantly share code, notes, and snippets.

@x5lcfd
Created May 18, 2018 13:06
Show Gist options
  • Save x5lcfd/d82c4273ac8cd2c02a17ed36d36bdc60 to your computer and use it in GitHub Desktop.
Save x5lcfd/d82c4273ac8cd2c02a17ed36d36bdc60 to your computer and use it in GitHub Desktop.
void SyncGameObjectWithUIElement(Vector3 entityPos, Canvas canvas, RectTransform parentRectTransform, RectTransform targetRectTransform)
{
Vector3 screenPos = Camera.main.WorldToScreenPoint(entityPos);
entityPos = screenPos / canvas.scaleFactor;
Rect rect = parentRectTransform.rect;
entityPos.x = entityPos.x - rect.width * 0.5f;
entityPos.y = entityPos.y - rect.height * 0.5f;
entityPos.z = 0;
//targetRectTransform.anchoredPosition3D = entityPos;
targetRectTransform.anchoredPosition = new Vector2(entityPos.x, entityPos.y);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment