Author Topic: Scale a sprite to the same size of a 3D object  (Read 2008 times)

Zylann

  • Guest
Scale a sprite to the same size of a 3D object
« on: July 25, 2013, 08:53:02 AM »
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 :

  1.         private Vector3 SceneToUIPos(Vector3 scenePos)
  2.         {
  3.                 return uiCamera.ViewportToWorldPoint(
  4.                         Camera.mainCamera.WorldToViewportPoint(scenePos));
  5.         }
  6.        
  7.         private float RadiusOnUI(Transform obj)
  8.         {
  9.                 // Assumes the object has a scale of (1,1,1) and a sphere collider
  10.                
  11.                 float r = obj.collider.bounds.extents.x;
  12.                 Vector3 objPos = transform.position + obj.collider.bounds.center;
  13.  
  14.                 // Take center and edge positions to compute the on-UI-space radius
  15.                 Vector3 a = SceneToUIPos(objPos);
  16.                 objPos += r * Camera.mainCamera.transform.right;
  17.                 Vector3 b = SceneToUIPos(objPos);
  18.                 return Vector3.Distance(a, b);
  19.         }
  20.        
  21.         ...
  22.        
  23.         float diameter = RadiusOnUI(catchObj);
  24.         // HelperCircle is a UISprite with a 256x256 texture
  25.         _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.

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: Scale a sprite to the same size of a 3D object
« Reply #1 on: July 26, 2013, 04:13:18 AM »
Lots of math. :P

Calculate the bounds of your object, calculate the on screen rect of those bounds, then resize the widget to match.