Newer
Older
Dreamsturbia-Project-IADE-Unity3D / Assets / Scripts / Mechanisms / MovingPlatform.cs
@Rackday Rackday on 21 Aug 2024 2 KB Project Added
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class MovingPlatform : MonoBehaviour
  5. {
  6. public ConditionCkecker conditionChecker;
  7. public Transform destination;
  8. public Transform origin;
  9. public float speed;
  10. private Transform endPoint;
  11. private float timer = 0;
  12. private bool positiveDirection;
  13. Dictionary<Collider, Transform> transformsParents = new Dictionary<Collider, Transform>();
  14. // Start is called before the first frame update
  15. void Start()
  16. {
  17. positiveDirection = true;
  18. transform.position = origin.position;
  19. if (!positiveDirection)
  20. {
  21. endPoint = origin;
  22. }
  23. else
  24. {
  25. endPoint = destination;
  26. }
  27. }
  28. // Update is called once per frame
  29. void Update()
  30. {
  31. if (conditionChecker.CheckConditions())
  32. {
  33. if (Vector3.Distance(transform.position, endPoint.position) > 0.1)
  34. {
  35. if (positiveDirection)
  36. {
  37. timer += Time.deltaTime * speed;
  38. } else
  39. {
  40. timer -= Time.deltaTime * speed;
  41. }
  42. transform.position = Vector3.MoveTowards(origin.position, destination.position, timer);
  43. } else
  44. {
  45. positiveDirection = !positiveDirection;
  46. if (!positiveDirection)
  47. {
  48. endPoint = origin;
  49. } else
  50. {
  51. endPoint = destination;
  52. }
  53. }
  54. }
  55. }
  56. public void OnReload()
  57. {
  58. timer = 0;
  59. endPoint = destination;
  60. }
  61. private void OnTriggerStay(Collider other)
  62. {
  63. if (!transformsParents.ContainsKey(other))
  64. {
  65. transformsParents.Add(other, other.transform.parent);
  66. }
  67. if (other.transform.parent != transform)
  68. {
  69. other.transform.SetParent(transform);
  70. }
  71. }
  72. private void OnTriggerExit(Collider other)
  73. {
  74. Transform tr;
  75. if (transformsParents.TryGetValue(other,out tr))
  76. {
  77. other.transform.SetParent(tr);
  78. transformsParents.Remove(other);
  79. }
  80. }
  81. }