using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class FallawayFloor : MonoBehaviour
{
    // // Speed at which the object moves towards the ground.
    public float speed;
    // Time it takes for ogjecct to begin moving towards the ground.
    public float fallAwayTime;
    public Material dissolve;
    
    [SerializeField] private Renderer _renderer;
    
    private Rigidbody rb;
    private Vector3 initialPosition;

    private void Start()
    {
        initialPosition = transform.position;
        
        // Get Rigidbody component.
        rb = GetComponent<Rigidbody>();
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            // Start the Destroy floor coroutine and switch to the dissolve material.
            StartCoroutine(Fall());
            _renderer.material = dissolve;
        }
    }

    private IEnumerator Fall()
    {
        // wait a moment
        yield return new WaitForSeconds(fallAwayTime);
        
        // fall
        rb.velocity = Vector3.down * speed;
    }

    public void Reset()
    {
        transform.position = initialPosition;
        rb.velocity = Vector3.zero;
    }
}
