SlopeExtras.cs 2.1 KB

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