maxhacker11

SquashAndStretch.cs

Sep 3rd, 2023
3,751
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.25 KB | Source Code | 0 0
  1. using UnityEngine;
  2.  
  3. public class SquashAndStretch : MonoBehaviour
  4. {
  5.     public Transform Sprite;
  6.     public float Stretch = 0.1f;
  7.     [SerializeField] private Transform squashParent;
  8.  
  9.     private Rigidbody2D _rigidbody;
  10.     private Vector3 _originalScale;
  11.  
  12.     private void Start()
  13.     {
  14.         _rigidbody = GetComponent<Rigidbody2D>();
  15.         _originalScale = Sprite.transform.localScale;
  16.  
  17.         if(!squashParent)
  18.             squashParent = new GameObject(string.Format("_squash_{0}", name)).transform;
  19.     }
  20.  
  21.     private void Update()
  22.     {
  23.         Sprite.parent = transform;
  24.         Sprite.localPosition = Vector3.zero;
  25.         Sprite.localScale = _originalScale;
  26.         Sprite.localRotation = Quaternion.identity;
  27.  
  28.         squashParent.localScale = Vector3.one;
  29.         squashParent.position = transform.position;
  30.  
  31.         Vector3 velocity = _rigidbody.velocity;
  32.         if (velocity.sqrMagnitude > 0.01f)
  33.         {
  34.             squashParent.rotation = Quaternion.FromToRotation(Vector3.right, velocity);
  35.         }
  36.  
  37.         var scaleX = 1.0f + (velocity.magnitude * Stretch);
  38.         var scaleY = 1.0f / scaleX;
  39.         Sprite.parent = squashParent;
  40.         squashParent.localScale = new Vector3(scaleX, scaleY, 1.0f);
  41.     }
  42. }
  43.  
Advertisement
Add Comment
Please, Sign In to add comment