using UnityEngine;
using System.Collections;

public class OpenGate : MonoBehaviour 
{
	public bool stayOpen;

	float speed = 5f;
	public Transform gate;
	public Transform moveTo;
	Vector3 moveToPos;
	public Transform moveToClose;
	Vector3 moveToPosClose;
	bool open;
	bool close;
	
	void Start()
	{
		moveToPos = moveTo.transform.position;
		moveToPosClose = moveToClose.position;
	}
	
	void OnTriggerEnter2D(Collider2D col)
	{
		if(col.gameObject.tag == "Player1" || col.gameObject.tag == "Player2")
		{
			open = true;
		}
	}
	
	void OnTriggerExit2D(Collider2D col)
	{
		if((col.gameObject.tag == "Player1" || col.gameObject.tag == "Player2") && !stayOpen)
		{
			open = false;
			close = true;
		}
	}

	void Update()
	{
		if (open)
		{
			gate.transform.position = Vector3.MoveTowards(gate.transform.position, moveToPos, speed * Time.deltaTime);
			
			if (gate.transform.position == moveTo.transform.position)
			{
				open = false;
			}
		}	

		if (close)
		{
			gate.transform.position = Vector3.MoveTowards(gate.transform.position, moveToPosClose, speed * Time.deltaTime);
			
			if (gate.transform.position == moveToClose.transform.position)
			{
				close = false;
			}
		}
	}


}
