1

Scale

I am trying to scale a rectangle on the X axis and keep it's position the same as it was. Normally when you scale sprite or object in Unity3D it's from it's center and expands on both sides of the given axis. What i tried is:

  1. Scale the object on the X axis with some value.
  2. Reposition it half the given scaling size back.

When i perform these two steps, somehow i get near the desired result, but the object still expands with some very small amount on the opposite side.

private float m_scaleSize = 1.1600f;

private void Update()
{  
    transform.localPosition -= new Vector3(0, m_scaleSize / 2, 0) * Time.deltaTime;    
    transform.localScale += new Vector3(0, m_scaleSize, 0) * Time.deltaTime;     
}

Why am i getting almost the correct result? Is this some floating point imprecision or my math is totally wrong? I also want to point out that i am looking for the math solution and achieve this without parenting it to some other object in order to get this effect.

2 Answers 2

1

A common solution for this problem is to create an empty GameObject and position it at the point you want to scale from, then make your rectangle a child of it. When you scale the empty GameObject, the child will resize from the centre of it, rather than its own centre.

3
  • At the end of the question i pointed that i want to find out the solution without parenting the object to another and find out why this basic math does not work.
    – Mama Tate
    Dec 27, 2014 at 13:01
  • Your maths might not be working because you're performing an integer division, try m_scaleSize / 2f to do a floating point division and see if that helps. That said, I think the empty parent is a better solution.
    – Adam H
    Dec 27, 2014 at 13:04
  • It's not a floating point error i guess. Just tried it. Ill ask in unity answers. Thanks for trying to help.
    – Mama Tate
    Dec 27, 2014 at 13:14
0

Found out where the problem was hiding. Actually the math was correct, but when working with sprites, pixels from the actual sprite are converted to Unity units. So in my case the sprite rectangle was 128x128, but it's import settings "Pixels per unit:" was set to 100 which gave incorrect results in positioning and scaling. So basically i just made the rectangle a box which is 100x100pixels and it all worked out correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.