WalkRope.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using UnityEngine;
  2. [ExecuteInEditMode]
  3. public class WalkRope : MonoBehaviour
  4. {
  5. public GameObject bridge;
  6. [HideInInspector]
  7. public MegaRopeDeform mod;
  8. public float offset = 0.0f; // Character offset
  9. public bool checkonbridge = false;
  10. public float weight = 1.0f;
  11. Mesh mesh;
  12. void LateUpdate()
  13. {
  14. if ( bridge )
  15. {
  16. // Get the bridge modifier
  17. if ( mod == null )
  18. mod = bridge.GetComponent<MegaRopeDeform>();
  19. if ( mesh == null )
  20. {
  21. MeshFilter mf = bridge.GetComponent<MeshFilter>();
  22. mesh = mf.sharedMesh;
  23. }
  24. if ( mod && mesh )
  25. {
  26. int ax = (int)mod.axis;
  27. Vector3 pos = transform.position;
  28. // Get into local space
  29. Vector3 lpos = mod.transform.worldToLocalMatrix.MultiplyPoint(pos);
  30. bool onbridge = true;
  31. if ( checkonbridge )
  32. {
  33. if ( lpos.x > mesh.bounds.min.x && lpos.x < mesh.bounds.max.x && lpos.z > mesh.bounds.min.z && lpos.z < mesh.bounds.max.z )
  34. onbridge = true;
  35. else
  36. onbridge = false;
  37. }
  38. // Are we on the bridge
  39. if ( onbridge )
  40. {
  41. // How far across are we
  42. float alpha = (lpos[ax] - mod.soft.masses[0].pos.x) / (mod.soft.masses[mod.soft.masses.Count - 1].pos.x - mod.soft.masses[0].pos.x);
  43. if ( alpha > 0.0f || alpha < 1.0f )
  44. {
  45. Vector2 rpos = mod.SetWeight(lpos[ax], weight);
  46. lpos.y = rpos.y + (offset * 0.01f); // 0.01 is just to make inspector easier to control in my test scene which is obvioulsy very small
  47. transform.position = bridge.transform.localToWorldMatrix.MultiplyPoint(lpos);
  48. }
  49. }
  50. else
  51. {
  52. SetPos(mod, 0.0f);
  53. }
  54. }
  55. }
  56. }
  57. public void SetPos(MegaRopeDeform mod, float alpha)
  58. {
  59. mod.weightPos = alpha * 100.0f;
  60. mod.weight = weight;
  61. }
  62. }