MegaWalkBridge.cs 2.1 KB

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