SlopeExtras.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using Controller.Bicycle;
  3. using UnityEngine;
  4. namespace Roads
  5. {
  6. [RequireComponent(typeof(StraightRoadExtras))]
  7. public class SlopeExtras : MonoBehaviour
  8. {
  9. private const float TOLERANCE_ANGLE = 1f;
  10. private StraightRoadExtras straightRoadExtras;
  11. private BikeSpeedBooster booster;
  12. public bool firstOrLast;
  13. private Vector3 lowerPos;
  14. private Vector3 upperPos;
  15. private int slopePrefix = 0;
  16. private bool isFirst = false;
  17. private void OnEnable()
  18. {
  19. straightRoadExtras = GetComponent<StraightRoadExtras>();
  20. // the origin of a road tile is always on the lower end.
  21. var t = transform;
  22. lowerPos = t.position;
  23. upperPos = lowerPos + t.right * t.localScale.x;
  24. booster = BikeSpeedBooster.Instance;
  25. }
  26. private void OnTriggerEnter(Collider other)
  27. {
  28. if (other.CompareTag("bike"))
  29. {
  30. var bikePos = other.ClosestPointOnBounds(lowerPos);
  31. if ((bikePos - lowerPos).magnitude < (bikePos - upperPos).magnitude)
  32. {
  33. //coming from lower pos -> uphill
  34. slopePrefix = 1;
  35. }
  36. else
  37. {
  38. slopePrefix = -1;
  39. }
  40. var directedSlope = slopePrefix * straightRoadExtras.SlopeDeg;
  41. booster.SetFixedBoostForSlope(directedSlope);
  42. isFirst = other.transform.rotation.eulerAngles.x < TOLERANCE_ANGLE;
  43. if (firstOrLast && isFirst)
  44. {
  45. booster.AddBoosterForFirstAndSlope(directedSlope);
  46. }
  47. }
  48. }
  49. private void OnTriggerExit(Collider other)
  50. {
  51. //Debug.Log($"EXIT bike rotation = {other.transform.rotation.eulerAngles}");
  52. if (other.CompareTag("bike") && firstOrLast)
  53. {
  54. var isLast = !isFirst && other.transform.rotation.eulerAngles.x > TOLERANCE_ANGLE;
  55. if(!isLast) return;
  56. booster.AddBoosterForLastAndSlope(slopePrefix * straightRoadExtras.SlopeDeg);
  57. booster.ResetFixedBoost(); //on straight road again
  58. }
  59. }
  60. }
  61. }