WalkBridge.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 
  2. using UnityEngine;
  3. [ExecuteInEditMode]
  4. public class WalkBridge : MonoBehaviour
  5. {
  6. public GameObject bridge;
  7. [HideInInspector]
  8. public MegaCurveDeform mod;
  9. public float offset = 0.0f; // Character offset
  10. public float smooth = 0.0f;
  11. void Update()
  12. {
  13. if ( bridge )
  14. {
  15. // Get the bridge modifier
  16. if ( mod == null )
  17. mod = bridge.GetComponent<MegaCurveDeform>();
  18. if ( mod )
  19. {
  20. int ax = (int)mod.axis;
  21. Vector3 pos = transform.position;
  22. // Get into local space
  23. Vector3 lpos = mod.transform.worldToLocalMatrix.MultiplyPoint(pos);
  24. // Are we on the bridge
  25. if ( lpos.x > mod.bbox.min.x && lpos.x < mod.bbox.max.x && lpos.z > mod.bbox.min.z && lpos.z < mod.bbox.max.z )
  26. {
  27. // How far across are we
  28. float alpha = (lpos[ax] - mod.bbox.min[ax]) / (mod.bbox.max[ax] - mod.bbox.min[ax]);
  29. // Deform the bridge
  30. SetPos(mod, alpha);
  31. // Place object on deformed bridge
  32. lpos.y = mod.GetPos(alpha) + (offset * 0.01f); // 0.01 is just to make inspector easier to control in my test scene which is obvioulsy very small
  33. transform.position = bridge.transform.localToWorldMatrix.MultiplyPoint(lpos);
  34. }
  35. else
  36. SetPos(mod, 0.0f);
  37. }
  38. }
  39. }
  40. private float easeInOutSine(float start, float end, float value)
  41. {
  42. end -= start;
  43. return -end / 2.0f * (Mathf.Cos(Mathf.PI * value / 1.0f) - 1.0f) + start;
  44. }
  45. // Change the keys
  46. public void SetPos(MegaCurveDeform mod, float alpha)
  47. {
  48. float val = 0.0f;
  49. if ( alpha < 0.5f )
  50. val = easeInOutSine(0.0f, -mod.MaxDeviation * 0.01f, alpha / 0.5f);
  51. else
  52. val = easeInOutSine(-mod.MaxDeviation * 0.01f, 0.0f, (alpha - 0.5f) / 0.5f);
  53. mod.SetKey(0, 0.0f, 0.0f, Mathf.Tan(0.0f), Mathf.Tan(Mathf.Atan2(val, alpha)));
  54. float inTangent = Mathf.Lerp(Mathf.Tan(0.0f), Mathf.Tan(Mathf.Atan2(val, alpha)), smooth);
  55. float outTangent = Mathf.Lerp(Mathf.Tan(Mathf.PI), Mathf.Tan(Mathf.Atan2(val, alpha - 1.0f)), smooth);
  56. mod.SetKey(1, Mathf.Clamp(alpha, 0.001f, 0.999f), val, inTangent, outTangent);
  57. mod.SetKey(2, 1.0f, 0.0f, Mathf.Tan(Mathf.Atan2(-val, 1.0f - alpha)), Mathf.Tan(Mathf.PI));
  58. }
  59. }