Wobble.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class Wobble : MonoBehaviour
  5. {
  6. Renderer rend;
  7. Vector3 lastpos;
  8. Vector3 velocity;
  9. Vector3 lastRot;
  10. Vector3 angularVelocity;
  11. public float MaxWobble = 0.03f;
  12. public float WobbleSpeed = 1f;
  13. public float Recovery = 1f;
  14. float wobbleAmountX;
  15. float wobbleAmountZ;
  16. float wobbleAmountToAddX;
  17. float wobbleAmountToAddZ;
  18. float pulse;
  19. float time = 0.5f;
  20. // Start is called before the first frame update
  21. void Start()
  22. {
  23. rend = GetComponent<Renderer>();
  24. }
  25. // Update is called once per frame
  26. void Update()
  27. {
  28. time += Time.deltaTime;
  29. //decrease wobble over time
  30. wobbleAmountToAddX = Mathf.Lerp(wobbleAmountToAddX, 0, Time.deltaTime * (Recovery));
  31. wobbleAmountToAddZ = Mathf.Lerp(wobbleAmountToAddZ, 0, Time.deltaTime * (Recovery));
  32. // make a sine wave of the decreasing wobble
  33. pulse = 2 * Mathf.PI * WobbleSpeed;
  34. wobbleAmountX = wobbleAmountToAddX * Mathf.Sin(pulse * time);
  35. wobbleAmountZ = wobbleAmountToAddZ * Mathf.Sin(pulse * time);
  36. //send it to the shader
  37. rend.material.SetFloat("_WobbleX", wobbleAmountX);
  38. rend.material.SetFloat("_WobbleZ", wobbleAmountZ);
  39. velocity = (lastpos - transform.position) / Time.deltaTime;
  40. angularVelocity = transform.rotation.eulerAngles - lastRot;
  41. // add clamped velocity to wobble
  42. wobbleAmountToAddX += Mathf.Clamp((velocity.x + (angularVelocity.z * 0.2f)) * MaxWobble, -MaxWobble, MaxWobble);
  43. wobbleAmountToAddZ += Mathf.Clamp((velocity.z + (angularVelocity.x * 0.2f)) * MaxWobble, -MaxWobble, MaxWobble);
  44. lastpos = transform.position;
  45. lastRot = transform.rotation.eulerAngles;
  46. }
  47. }