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

public class PlayerRespawn : MonoBehaviour
{
    GameObject[] respawnPoints;
    int lastRespawn = 0;

    // Start is called before the first frame update
    void Start()
    {
        respawnPoints = GameObject.FindGameObjectsWithTag("SpawnPoint");
        transform.position = respawnPoints[0].transform.position;
    }

    private void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.CompareTag("DeathZone"))
        {
            Respawn();
        }
        if (other.gameObject.CompareTag("SpawnPoint"))
        {
            //set this one as new spawn point
            for(int i = 0; i < respawnPoints.Length; i++)
            {
                if (other.gameObject.name == respawnPoints[i].name)
                {
                    lastRespawn = i;
                    Debug.Log("Respawn point changed into: " + other.gameObject.name);
                }
            }
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("SpawnPoint"))
        {
            //set this one as new spawn point
            for (int i = 0; i < respawnPoints.Length; i++)
            {
                if (other.gameObject.name == respawnPoints[i].name)
                {
                    lastRespawn = i;
                    Debug.Log("Respawn point changed into: " + other.gameObject.name);
                }
            }
        }
    }

    public void Respawn()
    {
        //respawn in last respawn point
        transform.position = respawnPoints[lastRespawn].transform.position;
    }
}
