- Home /
Sprite scale and world scale
Hello everyone,
Searching for hours now. I basically want to scale a sprite ( Unity 4.3 ) by setting a world pos.
I'm searching for proportinal values but can't obtain something satisfying.
So basically I want something like gameObject.transform.localScale.x = 228 * ratio
Thanks in advance for any maths help :)
Edit:
Further explanations:
I have a simple Cube created in hierarchy which has a scale x and y of 45.
I have a sprite created from a texture ( 128 x 64 ) that I want to be exactly as big as the cube ( so 45 x 45 in world pos )
How can I, in code, calculate the ratio between the 100 x 100 values of the sprite scale in the inspector to the 45 x 45 worldspace pos that I want?
My sprites are in 100 pixelsToUnits.
My camera ortho size is half my screen height, so 500 actually.
I'm puzzled by some things in your question. I don't know what you mean by 'scale a sprite by setting a world pos'. I also don't understand the 'ratio' you are looking for. ]
If you select your sprite texture in the Inspector, you will see a 'Pixels to Units' setting. This is the conversion factor for how big your sprite will be in world space when the sprite is scaled to (1,1,1).
$$anonymous$$y bad for crappy description of my problem. Edited my original question for more informations
Answer by robertbu · Feb 14, 2014 at 09:38 AM
You can get the world size of your sprite from the Sprite.bounds. You can divide that size by your target size to get the size to set Transform.localScale. So if we wanted to set a sprite to be 45 units wide, we could do:
#pragma strict
function Start () {
var bounds : Bounds = GetComponent(SpriteRenderer).sprite.bounds;
var xSize = bounds.size.x;
transform.localScale.x = 45.0 / xSize;
}
Can't believe it was that simple... Well thank you so much you definitely made my day!
The documentation for sprite.bounds (http://docs.unity3d.com/ScriptReference/Bounds.html) says it returns an axis-aligned box. That won't match the sprite's actual bounds if it's rotated. Furthermore, if the sprite is scaled, sprite.bounds doesn't appear to reflect that. Does anyone know an alternative that reports the sprite's bounds in non-axis-aligned local coordinates?
Your answer
Follow this Question
Related Questions
Sprite Rendering Cost Calculation 1 Answer
Background Sprite Setting 0 Answers
Apply shader to a sprite. 3 Answers
Jelly Object for 2D Game 2 Answers