I have an object with a sphereCollider in my scene, and a 2D sprite on my GUI.
I managed to position the sprite right over the object, but I want the sprite to have the same width as the sphere in the scene.
I tried projecting the center and a point on the surface of the sphere to get an on-gui distance,
and then using it as localScale value, but it doesn't works at all (it's ridiculously small).
How can I achieve that?
Here is the code I'm currently using :
private Vector3 SceneToUIPos(Vector3 scenePos)
{
return uiCamera.ViewportToWorldPoint(
Camera.mainCamera.WorldToViewportPoint(scenePos));
}
private float RadiusOnUI(Transform obj)
{
// Assumes the object has a scale of (1,1,1) and a sphere collider
float r = obj.collider.bounds.extents.x;
Vector3 objPos = transform.position + obj.collider.bounds.center;
// Take center and edge positions to compute the on-UI-space radius
Vector3 a = SceneToUIPos(objPos);
objPos += r * Camera.mainCamera.transform.right;
Vector3 b = SceneToUIPos(objPos);
return Vector3.Distance(a, b);
}
...
float diameter = RadiusOnUI(catchObj);
// HelperCircle is a UISprite with a 256x256 texture
_helperCircle
.transform.localScale = new Vector3
(diameter, diameter,
1);
Note: I know there is a little bias due to the perspective projection (a sphere is not really a perfect circle when projected), but I only need an average accuracy.