- Home /
Unity streching sprite gameobject to fit two positions.
Hello.
I have a sprite gameobject, which I want to scale by x axis in order to fit it between two points.
I have this script:
public void strechBetween(Vector2 point1, Vector2 point2)
{
Vector3 scale = transform.localScale;
scale.x = Vector3.Distance(point1, point2);
transform.localScale = scale;
}
But it streches to much. Is there any other solutions?
Answer by DavidWatts · Aug 28, 2016 at 05:41 AM
I haven't tested this but you are forgetting to factor in the size of the sprite in units. try this
public void strechBetween(Vector2 point1, Vector2 point2)
{
float spriteSize = GetComponent<SpriteRenderer>.sprite.rect.width / GetComponent<SpriteRenderer>.sprite.pixelsPerUnit;
Vector3 scale = transform.localScale;
scale.x = (point1.x - point2.x) / spriteSize;
transform.localScale = scale;
}
@$$anonymous$$Watts Oh I forgot. This worked, but with scale.x = Vector3.Distance(point1, point2) / spriteSize;
Please write it as answer so I could accept it.
yea you should probably use $$anonymous$$athf.Abs( point1.x - point2.x ) / spriteSize i forgot to put that in. that way it will still work if the y values of the points are different.
Your answer
Follow this Question
Related Questions
Is there a way to change the sprite for all instances of the same object simultaneously? 1 Answer
How do i change a sprite when another gameobject with the same prefab is colliding / is near 1 Answer
Change sprite color on GameObjects from a list. 1 Answer
Prefabs and multiple tilesets? 0 Answers
How do i change a sprite when another gameobject with the same prefab is colliding / is near 1 Answer