- Home /
Other
Move object by the size of the object? (Unity2D)
I am trying to move a sprite by its height.The Code I am using is:
Vector2 pos = transform.position;
transform.position= new Vector2 (pos.x, pos.y + transform.localScale.y);
But the sprite is not moving completely by the size, it stops at somewhere above middle.
The code works fine for simple(eg square) sprites created inside Unity. But it is not working for imported sprites. It gives different result for different sprite.
The scale has nothing to do with the size of the sprite. It could be 10 units wide and the scale would and should still be 1 on that axis.
What you need to read is the actual sprite width (in case of X axis, IF you're talking about axis alignement) divided by the used pixels per units. that's the actual world space width of the sprite.
I added this:
GetComponent ().sprite.rect.width / 100;
sprite have 100 pixel per unit
still not working
Answer by YBtheS · Jul 02, 2018 at 09:38 PM
I think you are looking for Sprite.bounds.size.y (see this) instead of Transform.localScale.y. The local scale for sprites does not represent the true size as it is the size factor, not the measured size (if that makes sense).
Its not working same result.
Vector2 pos = transform.position;
transform.position= new Vector2 (pos.x, pos.y + transform.GetComponent<SpriteRenderer>().sprite.bounds.size.y);
That's odd. Is that code within an Update, FixedUpdate, or another recurring method? If not, that won't work as the size will never update. Also are you sure that you are changing the size of the sprite visually and not just the size of the game object?