- Home /
How can I accurately convert a Game Object's position to a sub Canvas/Rect screen position?
Basically I am trying to position a black square (UI Element on the Canvas) at the same position as an object that the camera has focused on. The camera is attached to an aircraft which moves above the world space land that has various game objects. I have a RaycastHit that goes from the center of the camera's frustum out to the world where it registers all game object colliders and returns the GameObject VisualTarget for whichever hit.collider.gameobject it detects, this becomes the Target. In an attempt to have the black square track the targets position, I tried the following code:
Failed attempts at tracking the object accurately
FocusTrack.transform.localPosition = RectTransformUtility.WorldToScreenPoint(mts.activeCamera, mts.VisualTarget.transform.position);
FocusTrack.transform.localPosition=(mts.activeCamera.WorldToScreenPoint(mts.VisualTarget.transform.position));
The raycast used to get the collider positions
Ray ray = activeCamera.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100000f, ~(1 << 9 | 12)))
{
Debug.DrawLine(activeCamera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0)), hit.point,Color.blue);
if (!hit.transform.name.Contains("Node"))
{
print("I'm looking at " + hit.transform.name);
VisualTarget = hit.transform.gameObject;
if (hit.collider.gameObject.GetComponent<MeshRenderer>() != null)
{
//hit.collider.gameObject.GetComponent<MeshRenderer>().material.color = Color.green;
//GetComponentInParent<Aircraft>().appManager.uiHud.SOC.GetComponent<SOC>().Track.transform.position = activeCamera.ViewportToWorldPoint(hit.point);
}
else if (hit.collider.gameObject.GetComponentInChildren<MeshRenderer>() != null) {
//hit.collider.gameObject.GetComponentInChildren<MeshRenderer>().material.color = Color.green;
}
}
else
print("No object in viewpoint or no colliders detected.");
}
So far it only somewhat tracks where the object is on the screen, but it is not very accurate at all and also tends to change its position (black box UI) depending on my current zoom level of the camera. A good working example would be:
User locates the target.
User grows a track on the target (black box) at it's center; the target is static, the user is moving
If the user pans to the left, the black box, along with the target will appear more to the right
If the user grows a track on the target and pans out of the target's view, the user shouldn't see the black box
The black box stays at it's target's center at all times