| | | 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; |
| | 13 | 12 | | [SerializeField] private float MaxWobble = 0.03f; |
| | 13 | 13 | | [SerializeField] private float WobbleSpeed = 1f; |
| | 13 | 14 | | [SerializeField] private float Recovery = 1f; |
| | | 15 | | float wobbleAmountX; |
| | | 16 | | float wobbleAmountZ; |
| | | 17 | | float wobbleAmountToAddX; |
| | | 18 | | float wobbleAmountToAddZ; |
| | | 19 | | float pulse; |
| | 13 | 20 | | float time = 0.5f; |
| | | 21 | | |
| | | 22 | | // Use this for initialization |
| | | 23 | | void Start() |
| | 6 | 24 | | { |
| | 6 | 25 | | rend = GetComponent<Renderer>(); |
| | 6 | 26 | | } |
| | | 27 | | private void Update() |
| | 8888 | 28 | | { |
| | 8888 | 29 | | time += Time.deltaTime; |
| | | 30 | | // decrease wobble over time |
| | 8888 | 31 | | wobbleAmountToAddX = Mathf.Lerp(wobbleAmountToAddX, 0, Time.deltaTime * (Recovery)); |
| | 8888 | 32 | | wobbleAmountToAddZ = Mathf.Lerp(wobbleAmountToAddZ, 0, Time.deltaTime * (Recovery)); |
| | | 33 | | |
| | | 34 | | // make a sine wave of the decreasing wobble |
| | 8888 | 35 | | pulse = 2 * Mathf.PI * WobbleSpeed; |
| | 8888 | 36 | | wobbleAmountX = wobbleAmountToAddX * Mathf.Sin(pulse * time); |
| | 8888 | 37 | | wobbleAmountZ = wobbleAmountToAddZ * Mathf.Sin(pulse * time); |
| | | 38 | | |
| | | 39 | | // send it to the shader |
| | 8888 | 40 | | rend.material.SetFloat("_WobbleX", wobbleAmountX); |
| | 8888 | 41 | | rend.material.SetFloat("_WobbleZ", wobbleAmountZ); |
| | | 42 | | |
| | | 43 | | // velocity |
| | 8888 | 44 | | velocity = (lastPos - transform.position) / Time.deltaTime; |
| | 8888 | 45 | | angularVelocity = transform.rotation.eulerAngles - lastRot; |
| | | 46 | | |
| | | 47 | | |
| | | 48 | | // add clamped velocity to wobble |
| | 8888 | 49 | | wobbleAmountToAddX += Mathf.Clamp((velocity.x + (angularVelocity.z * 0.2f)) * MaxWobble, -MaxWobble, MaxWobble); |
| | 8888 | 50 | | wobbleAmountToAddZ += Mathf.Clamp((velocity.z + (angularVelocity.x * 0.2f)) * MaxWobble, -MaxWobble, MaxWobble); |
| | | 51 | | |
| | | 52 | | // keep last position |
| | 8888 | 53 | | lastPos = transform.position; |
| | 8888 | 54 | | lastRot = transform.rotation.eulerAngles; |
| | 8888 | 55 | | } |
| | | 56 | | |
| | | 57 | | |
| | | 58 | | |
| | | 59 | | } |