- Home /
 
Unity Stretch Sprite between two Points at runtime
How to stretch a Sprite between two points say initialPosition , FinalPosition in world coordinates, Please elaborate with code, Thanks
Answer by jenci1990 · Dec 01, 2014 at 11:36 PM
 using UnityEngine;
 using System.Collections;
 
 public class Player : MonoBehaviour {
     public Vector3 startPosition = new Vector3(0f,0f,0f);
     public Vector3 endPosition = new Vector3(5f, 1f, 0f);
     public bool mirrorZ = true;
     void Start() {
         Strech(gameObject, startPosition, endPosition, mirrorZ);
     }
 
 
     public void Strech(GameObject _sprite,Vector3 _initialPosition, Vector3 _finalPosition, bool _mirrorZ) {
         Vector3 centerPos = (_initialPosition + _finalPosition) / 2f;
         _sprite.transform.position = centerPos;
         Vector3 direction = _finalPosition - _initialPosition;
         direction = Vector3.Normalize(direction);
         _sprite.transform.right = direction;
         if (_mirrorZ) _sprite.transform.right *= -1f;
         Vector3 scale = new Vector3(1,1,1);
         scale.x = Vector3.Distance(_initialPosition, _finalPosition);
         _sprite.transform.localScale = scale;
     }
 }
 
              That worked for med too, though I had to multiply scale.x with 100. Thanks
Worked for me too, i only had to divide scale.y by 100, thank you very mush.
Had to take in consideration the length of the original image and divide by the scale for it to work for me:
 float width = obj.GetComponent().bounds.size.x;
         Vector3 centerPos = (initialPosition + finalPosition) / 2f;
         obj.transform.position = centerPos;
         Vector3 direction = finalPosition - initialPosition;
         direction = Vector3.Normalize(direction);
         obj.transform.right = direction;
         if (mirrorZ) obj.transform.right *= -1f;
         Vector3 scale = new Vector3(1, 1, 1);
         scale.x = Vector3.Distance(initialPosition, finalPosition)/ width;
         obj.transform.localScale = scale;
 
                 Answer by BlackManta · Dec 02, 2014 at 12:23 AM
It would be difficult to do it from the sprite, From what I have used with sprites you could change the scale, rotation and position and such to make it fit between two points but using to points to find that would be a little trickier. (I suppose if you wanted to do the math you could derive your own rotation and scales from the two points.)
If a GUI is an option you could use this:
 GUI.DrawTexture (new Rect (<X1>, <Y2>, <X1>-<X2>, <Y1>-<y2>), MySprite.texture, ScaleMode.ScaleToFit);
 
               Hope that helps. Cheers, BM
Your answer
 
             Follow this Question
Related Questions
How can I get the height of a sprite? 1 Answer
2D character face another character 2 Answers
How to change the textureRect of a Sprite with a dynamic way? 0 Answers
how to decrease vertices number of a sprite 0 Answers
Create a Sprite Animation in Code 0 Answers