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

public class CameraFollow : MonoBehaviour {

	public float CameraDistance = -10;
	public float TransitionSpeed = 12;
	public Transform CurrentlyPossessed;
	Transform CameraTransform;
	float CurrentlyPossessed_x;
	float CurrentlyPossessed_y;
	Transform TempPossessed;

	void Start () {
		
		CameraTransform = this.transform;
		CurrentlyPossessed = GameObject.FindGameObjectWithTag("Possessed").transform;

	}
	
	void Update () {

		if (CurrentlyPossessed == null || CurrentlyPossessed.gameObject.tag != "Possessed") {
			
			TempPossessed = GameObject.FindGameObjectWithTag("Possessed").transform;
			CameraTransform.position = Vector3.MoveTowards(CameraTransform.position, TempPossessed.position + new Vector3(0,0,CameraDistance), 12f*Time.deltaTime);	
			StartCoroutine(ChangeTarget());

		}

		CurrentlyPossessed_x = CurrentlyPossessed.position.x;
		CurrentlyPossessed_y = CurrentlyPossessed.position.y;
		
		if (TempPossessed == null)
			CameraTransform.position = new Vector3(CurrentlyPossessed_x, CurrentlyPossessed_y, CameraDistance);
		
	}

	IEnumerator ChangeTarget() {

		yield return new WaitUntil(() => CameraTransform.position == TempPossessed.position + new Vector3(0,0,CameraDistance));

		CurrentlyPossessed = GameObject.FindGameObjectWithTag("Possessed").transform;
		TempPossessed = null;
		
	}


}
