- Home /
How to drag and stretch a 2D sprite
I want to drag and stretch a sprite in unity. To do this, I have created a Custom Plane with a texture and added this script to that plane:
private Vector2 _pointerStart;
private Vector3 _sizeStart;
private Vector3 _scaleStart;
private Vector3 _positionStart;
private void OnMouseDown() {
_pointerStart = Camera.main.ScreenToWorldPoint(Input.mousePosition);
_sizeStart = GetComponent < Renderer > ().bounds.size;
_scaleStart = transform.localScale;
_pointerStart = transform.position;
}
void Update() {
if (Input.GetMouseButton(0)) {
var pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
pos.z = 0.0f;
var dir = pos - transform.position;
transform.rotation = Quaternion.FromToRotation(Vector3.right, dir);
}
}
void OnMouseDrag() {
var pointerTravel = (Vector2) Camera.main.ScreenToWorldPoint(Input.mousePosition) - _pointerStart;
float newScale = Mathf.Abs(pointerTravel.x * _scaleStart.x);
transform.localScale = new Vector3(newScale, _sizeStart.y, _sizeStart.z);
}
This is working well with the rotation of the mouse and stretching when the mouse position is in the x axis, the problem is the y axis, the more the mouse get closer to the y axis, the more the sprite reduces it's scale. How can I solve this problem or there is a better way to implement this functionality?
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613011808im_/https://answers.unity.com/themes/thub/images/avi.jpg)