using System.Collections; using UnityEngine; using Game; using Music; using Player; namespace Game { /// /// This class controls platforms that fall when touched by a player or another platform. /// The platform will fall after a delay and then reset to its original position. /// public class FallPlatform : MonoBehaviour { /// /// The time (in seconds) before the platform starts falling after being triggered. /// public float fallDelay = 2f; /// /// The time (in seconds) before the platform resets to its original position after falling. /// public float resetDelay = 4f; /// /// Indicates whether the platform is currently falling. /// private bool falling; /// /// Reference to the Rigidbody2D component of the platform's parent object. /// private Rigidbody2D rb; /// /// The original position of the platform's parent object. /// private Vector3 defposition; /// /// Initializes the platform's Rigidbody2D and stores its original position. /// private void Start() { defposition = transform.parent.position; rb = transform.parent.GetComponent(); } /// /// Triggers the platform to fall when a player or another platform touches it. /// /// The object that collided with the platform. private void OnTriggerEnter2D(Collider2D collision) { try { // Check if the collision is caused by a player or another falling platform if (collision.transform.childCount != 0 && !falling && (collision.gameObject.CompareTag("Player") || collision.transform.GetChild(0).TryGetComponent(out FallPlatform _))) { StartCoroutine(FallAfterDelay()); } } catch (System.Exception e) { Debug.LogError("Error in FallPlatform: " + e.Message); } } /// /// Makes the platform fall after a delay and resets it after another delay. /// /// An IEnumerator for coroutine execution. private IEnumerator FallAfterDelay() { falling = true; // Wait for the fall delay before making the platform fall yield return new WaitForSeconds(fallDelay); rb.bodyType = RigidbodyType2D.Dynamic; // Wait for the reset delay before resetting the platform yield return new WaitForSeconds(resetDelay); transform.parent.GetComponent().SetTrigger("respawn"); // Wait briefly before resetting the platform yield return new WaitForSeconds(0.5f); Respawn(); } /// /// Resets the platform to its original position and state. /// private void Respawn() { falling = false; // Set the platform back to a static state rb.bodyType = RigidbodyType2D.Static; // Reset the platform's position and rotation transform.parent.position = defposition; transform.parent.rotation = Quaternion.identity; } } }