Guest User

Wobble.cs

a guest
Apr 17th, 2018
18,237
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class Wobble : MonoBehaviour
  6. {
  7.     Renderer rend;
  8.     Vector3 lastPos;
  9.     Vector3 velocity;
  10.     Vector3 lastRot;  
  11.     Vector3 angularVelocity;
  12.     public float MaxWobble = 0.03f;
  13.     public float WobbleSpeed = 1f;
  14.     public float Recovery = 1f;
  15.     float wobbleAmountX;
  16.     float wobbleAmountZ;
  17.     float wobbleAmountToAddX;
  18.     float wobbleAmountToAddZ;
  19.     float pulse;
  20.     float time = 0.5f;
  21.    
  22.     // Use this for initialization
  23.     void Start()
  24.     {
  25.         rend = GetComponent<Renderer>();
  26.     }
  27.     private void Update()
  28.     {
  29.         time += Time.deltaTime;
  30.         // decrease wobble over time
  31.         wobbleAmountToAddX = Mathf.Lerp(wobbleAmountToAddX, 0, Time.deltaTime * (Recovery));
  32.         wobbleAmountToAddZ = Mathf.Lerp(wobbleAmountToAddZ, 0, Time.deltaTime * (Recovery));
  33.  
  34.         // make a sine wave of the decreasing wobble
  35.         pulse = 2 * Mathf.PI * WobbleSpeed;
  36.         wobbleAmountX = wobbleAmountToAddX * Mathf.Sin(pulse * time);
  37.         wobbleAmountZ = wobbleAmountToAddZ * Mathf.Sin(pulse * time);
  38.  
  39.         // send it to the shader
  40.         rend.material.SetFloat("_WobbleX", wobbleAmountX);
  41.         rend.material.SetFloat("_WobbleZ", wobbleAmountZ);
  42.  
  43.         // velocity
  44.         velocity = (lastPos - transform.position) / Time.deltaTime;
  45.         angularVelocity = transform.rotation.eulerAngles - lastRot;
  46.  
  47.  
  48.         // add clamped velocity to wobble
  49.         wobbleAmountToAddX += Mathf.Clamp((velocity.x + (angularVelocity.z * 0.2f)) * MaxWobble, -MaxWobble, MaxWobble);
  50.         wobbleAmountToAddZ += Mathf.Clamp((velocity.z + (angularVelocity.x * 0.2f)) * MaxWobble, -MaxWobble, MaxWobble);
  51.  
  52.         // keep last position
  53.         lastPos = transform.position;
  54.         lastRot = transform.rotation.eulerAngles;
  55.     }
  56.  
  57.  
  58.  
  59. }
RAW Paste Data