MegaBallBounce.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using UnityEngine;
  2. [ExecuteInEditMode]
  3. public class MegaBallBounce : MonoBehaviour
  4. {
  5. public float ground = 0.0f; // Ground position
  6. public float radius = 1.0f; // radius of the ball/object
  7. public float vel = 0.0f; // vertical velocity
  8. public float spring = 10.0f; // spring rate of the object
  9. public float py = 1.0f; // vertical position
  10. public float mass = 1.0f; // objects mass
  11. public float timescale = 1.0f; // time multiplier
  12. MegaStretch mod;
  13. MegaModifyObject modobj;
  14. // Simple physics timsetp
  15. void FixedUpdate()
  16. {
  17. float t = Time.fixedDeltaTime * timescale;
  18. float fy = -9.81f * t;
  19. if ( py < ground )
  20. fy += (spring * (ground - py)) / mass;
  21. vel += fy * t;
  22. py += vel * t;
  23. }
  24. void Update()
  25. {
  26. // Find the stretch mod
  27. if ( !mod )
  28. {
  29. mod = GetComponent<MegaStretch>();
  30. modobj = GetComponent<MegaModifyObject>();
  31. }
  32. if ( mod )
  33. {
  34. Vector3 pos = transform.position;
  35. float amt = py - ground;
  36. if ( amt > 0.0f )
  37. amt = 0.0f;
  38. float y = py;
  39. if ( y < ground )
  40. y = ground;
  41. if ( mod.amount == 0.0f && amt == 0.0f )
  42. modobj.enabled = false;
  43. else
  44. modobj.enabled = true;
  45. mod.amount = (amt / radius);
  46. pos.y = y;
  47. transform.position = pos;
  48. }
  49. }
  50. }
  51. // TODO: Signal to turn off after this pass, saves doing the check for 0