BallBounce.cs 1.3 KB

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