using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using com.ootii.Actors.AnimationControllers;
using com.ootii.Cameras;
using com.ootii.Input;
using AIBehavior;
using BreadcrumbAi;
using UnityEngine.EventSystems;
using JetBrains.Annotations;
using System.Collections.Generic;
//using NUnit.Framework;
using com.ootii.Actors;
using com.ootii.Actors.LifeCores;
using BeautifyEffect;
using FIMSpace.FLook;
using com.ootii.Helpers;
using com.ootii.Utilities.Debug;
using com.ootii.Geometry;

public class PlayerVitals : MonoBehaviour, IDataPersistence
{
	public Transform debugTransform;
	public GameObject bulletProjectile;
	public Transform bulletParent;
	public GameObject currentHitObject;
	public List<GameObject> currentHitObjects = new List<GameObject>();
	public float sphereRadius;
	public float knifeRadius;
	public float maxDistance;
	public LayerMask aimLayerMask;
	public LayerMask layerMask;
	public LayerMask obstacleMask;
	private Vector3 origin;
	private Vector3 direction;
	private float currentHitDistance;

	float damageTime = 1.0f; // every 1 second
	float currentDamageTime;
	float timePainSoundPlayed;

	public float reloadtime;
	public float fireRate = 0.8f;
	private float nextTimetoFire = 0f;
	private bool isReloading;
	private int bulletPerShot = 15; 
	private float inaccuracyDistance = 0.1f;

	public Transform firePoint;
	public Transform knifeHitPoint;
	public ParticleSystem muzzleFlash;
	public GameObject TentacleFxParent;
	public ParticleSystem[] TentaclesFX;
	public GameObject muzzleLight;
	public GameObject shotgun;

	public int maxAmmo;
	public int currentAmmo;

	public int damage;
	public int headshotDamage;
	public int knifeDamage = 2;

	public float aimSpeed = 1f;

	public Slider staminaSlider;
	public float Stamina;
	public float minStamina;
	public float currentStamina;
	private float StaminaRegenTimer = 0.0f;
	private const float StaminaDecreasePerFrame = 3.5f;
	private const float StaminaIncreasePerFrame = 3.0f;
	private const float StaminaTimeToRegen = 1.5f;

	public Slider healthSlider;
	public float Health;
	public float currentHealth;
	public bool isInjured;
	public GameObject bloodPrefab;
	public bool isCrouching;

	public Slider flashlightSlider;
	public float maxFlashlight = 100;
	public float flashlightFallRate;
	public float currentFlashlight;
	public float flashlightDistance;
	public float flashlightRadius;
	public Light LightSource;
	public bool LightOn;
	public bool GlowStickON;
	public AudioClip TurnOn;
	public AudioClip TurnOff;
	public AudioClip Healsound;
	public AudioClip Aiming;
	public AudioClip FireShot;
	public AudioClip ReloadSound;
	public AudioClip GunEmpty;
	public AudioClip BulletReloadSound;
	public AudioClip GasolineSound;
	public AudioClip DeathSound;
	public AudioClip DeathTragicMusic;
	public AudioClip GameOverUIMusic;
	public AudioClip Heartbeat;
	public AudioClip FrySound;
	public AudioClip headshotSound;
	public AudioClip knifeSound;
	public AudioClip knifeHitSound;
	public AudioSource weaponAudioSource;
	public AudioSource HeartbeatAudioSource;
	[SerializeField] AudioClip[] Painsounds;
	[SerializeField] AudioClip[] Hitsounds;
	private AudioSource audioSource;

	public GameObject Inventory;
	public CameraController camRig;
	public UnityInputSource InputSource;
	public GameObject Player;
	public GameObject Gameover;
	public Animator m_Animator;
	public Animator BloodScreenFx;
	public Animator stealthFX;
	public bool isDead;
	public bool isSuiciding;
	public MotionController motionController;
	public ActorController actorController;

	protected MotionController mMotionController = null;

	public CameraShake CamShake;

	public bool isAiming;
	public bool isSettingTrap;
	public bool isSliding;
	public bool isRunning;

	public Transform Bullet1, Bullet2, Bullet3, Bullet4, Bullet5, Bullet6, Bullet7, Bullet8;
	public Transform AmmoText;
	public GameObject ShotgunUI;
	public GameObject PlayerVitalsUI;
	public GameObject QuestUI;
	public GameObject GasolineUI;
	public GameObject KnifeUI;
	public GameObject Reticle;
	public GameObject RedReticle;
	public GameObject GasCan;
	public GameObject gasolineTrap;
	public GameObject GlowStick;
	public GameObject CharacterHead;
	public GameObject FlashlightPoint;
	public Slider gasolineSlider;
	public float maxGasoline = 100;
	public float currentGasoline;
	public int trainDestroyed;
	public int deathCount;
	public int fatalHeadShot;

	[HideInInspector]
	public NotificationUI MsgUI;

	private BreadcrumbAi.Ai ai;

	private GameObject[] zombies;
	private Transform closestZombie;

	private DemoEnemyControls zombieHealth;
	private CrawlerControls crawlerControls;
	private SpreadFire spreadFire;
	private EasterEgg easterEgg;
	private Beautify beautify;

	private InventoryManager InvManager;
	private CameraFilterPack_AAA_BloodOnScreen camBlood;
	private FLookAnimator fLook;
	private FearSystem fearSystem;
	private bool tentacleIsPlaying;
	private string BaseLayer;

	private Quaternion _lookRotation;
	private Vector3 _direction;
	private bool _1stPerson;
	private Camera mainCamera;

	private void Awake()
	{
		if (menuScript1.PlayerSelected == 0)
		{
			Health = 100;
			maxAmmo = 5;
			damage = 2;
			headshotDamage = 4;
			maxDistance = 8;
			Stamina = 100;
		}

		if (menuScript1.PlayerSelected == 1)
		{
			//Has Shotgun
			//Normal Health (100)
			//Normal Stamina (100)
			//Normal Sanity (20)
			//Low Damage (1-3)
			Health = 100;
			maxAmmo = 5;
			damage = 1;
			headshotDamage = 3;
			maxDistance = 8;
			Stamina = 100;
		}
		if (menuScript1.PlayerSelected == 2)
		{
			//Has Pistol
			//High Health (125)
			//Low Stamina (75)
			//High Sanity (30)
			//Medium Damage (3-5)
			Health = 125;
			maxAmmo = 8;
			damage = 3;
			headshotDamage = 5;
			maxDistance = 15;
			Stamina = 75;
		}
		if (menuScript1.PlayerSelected == 3)
		{
			//Has Pistol
			//Low Health (50)
			//High Stamina (125)
			//Low Sanity (20)
			//High Damage (5-7)
			Health = 50;
			maxAmmo = 8;
			damage = 5;
			headshotDamage = 7;
			maxDistance = 6;
			Stamina = 125;
		}
	}

	void Start()
	{
		Cursor.visible = false;
		isCrouching = false;
		//currentAmmo = 0;
		AmmoText.GetComponent<Text>().text = currentAmmo.ToString() + " / " + maxAmmo;

		healthSlider.interactable = false;
		healthSlider.maxValue = Health;
		//currentHealth = Health;
		healthSlider.value = currentHealth;

		staminaSlider.interactable = false;
		staminaSlider.maxValue = Stamina;
		//currentStamina = Stamina;
		staminaSlider.value = currentStamina;

		flashlightSlider.interactable = false;
		flashlightSlider.maxValue = maxFlashlight;
		flashlightSlider.value = currentFlashlight;
		//currentFlashlight = maxFlashlight;
		LightOn = false;
		LightSource.intensity = 0f;
		isInjured = false;
		LightSource = GetComponentInChildren<Light>();
		audioSource = GetComponent<AudioSource>();
		beautify = FindObjectOfType(typeof(Beautify)) as Beautify;

		Inventory.SetActive(false);
		Gameover.SetActive(false);
		CameraController camRig = gameObject.GetComponent<CameraController>();
		UnityInputSource InputSource = GetComponent<UnityInputSource>();
		m_Animator = gameObject.GetComponent<Animator>();
		m_Animator.SetBool("isDead", false);
		m_Animator.SetBool("isInjured", false);
		motionController = GetComponent<MotionController>();
		mMotionController = gameObject.GetComponent<MotionController>();

		CameraController lController = gameObject.GetComponent<CameraController>();

		CamShake = gameObject.GetComponent<CameraShake>();

		InvManager = FindObjectOfType(typeof(InventoryManager)) as InventoryManager;

		camBlood = Camera.main.GetComponent<CameraFilterPack_AAA_BloodOnScreen>();

		fLook = gameObject.GetComponent<FLookAnimator>();

		fearSystem = GetComponent<FearSystem>();

		//tentacleIsPlaying = false;
		TentaclesFX = TentacleFxParent.GetComponentsInChildren<ParticleSystem>();

		closestZombie = null;

		BaseLayer = "Base Layer";

		_1stPerson = false;

		mainCamera = Camera.main;

		//set weapon
		for (int t = 0; t < InvManager.Items; t++) //Starting a loop in the slots of the inventory:
		{
			if (InvManager.Slots[t].IsTaken == true) //Checking if there's an item in this slot.
			{
				Item ItemScript = InvManager.Slots[t].Item.GetComponent<Item>(); //Getting the item script from the items inside the bag.
				if (ItemScript.Name == "Shotgun" || ItemScript.Name == "Colt 1911") //Checking if the type of the new item matches with another item already in the bag.
				{
					shotgun.SetActive(true);
					ShotgunUI.SetActive(true);
				}
			}
		}

	}

	void Update()
	{

		SwitchState();
		StartCoroutine(ToggleCrouch());
		StartCoroutine(CheckGasoline());
		HandleTentacleFX();
		HandleReload();
		HandleAmmoUI();
		HandleGunFire();
		HandleStatsLock();
		HandleFlashlight();
		HandleStamina();
		HandleFirstPerson();

		//AIMING SOUND
		if (Input.GetMouseButtonDown(1) && shotgun.activeInHierarchy == true)
		{
			AudioClip clip = Aiming;
			weaponAudioSource.PlayOneShot(clip);

		}
		//HEALING CHEAT
		/*if(Input.GetKeyDown(KeyCode.H))
		{	
			MotionControllerMotion bandage = mMotionController.GetMotion(1, "IdleBandage");
			mMotionController.ActivateMotion(bandage); 
			currentHealth += 10;
			
			audioSource.PlayOneShot(Healsound);
			
			if (healthSlider.value >= 100)
			{
				currentHealth = Health;
				
			}
		}*/
	}

    private void FixedUpdate()
    {
		HandleAiming();
		HandleFlashlightPhysics();
        
    }

    private void HandleTentacleFX()
    {
		//TENTACLES FX
		if (fearSystem.isInsane || isSuiciding)
		{
			if (!tentacleIsPlaying)
			{
				foreach (ParticleSystem tentacle in TentaclesFX)
				{
					tentacle.Play();
					tentacle.loop = true;
					tentacleIsPlaying = true;
				}
			}
		}
		if (!fearSystem.isInsane)
		{
			if (tentacleIsPlaying)
			{
				foreach (ParticleSystem tentacle in TentaclesFX)
				{
					tentacleIsPlaying = false;
					tentacle.loop = false;
				}
			}
		}
	}
	private void HandleReload()
    {
		//GUN RELOAD
		if (shotgun.activeInHierarchy == true && !isSettingTrap && Input.GetKeyDown(KeyCode.R) || Input.GetKeyDown(KeyCode.JoystickButton3))
		{
			if (!isReloading)
			{

				StartCoroutine(Reload());
			}
		}
	}
	private void HandleAmmoUI()
    {
		//BULLET UI STRING
		AmmoText.GetComponent<Text>().text = currentAmmo.ToString() + " / " + maxAmmo;

		//BULLET UI SECTION
		if (currentAmmo > 0)
		{
			Bullet1.GetComponent<Image>().enabled = true;
		}

		else
		{
			Bullet1.GetComponent<Image>().enabled = false;
		}

		if (currentAmmo > 1)
		{
			Bullet2.GetComponent<Image>().enabled = true;
		}

		else
		{
			Bullet2.GetComponent<Image>().enabled = false;
		}

		if (currentAmmo > 2)
		{
			Bullet3.GetComponent<Image>().enabled = true;
		}

		else
		{
			Bullet3.GetComponent<Image>().enabled = false;
		}

		if (currentAmmo > 3)
		{
			Bullet4.GetComponent<Image>().enabled = true;
		}

		else
		{
			Bullet4.GetComponent<Image>().enabled = false;
		}

		if (currentAmmo > 4)
		{
			Bullet5.GetComponent<Image>().enabled = true;
		}

		else
		{
			Bullet5.GetComponent<Image>().enabled = false;
		}

		if (menuScript1.PlayerSelected == 2 || menuScript1.PlayerSelected == 3)
		{
			if (currentAmmo > 5)
			{
				Bullet6.GetComponent<Image>().enabled = true;
			}

			else
			{
				Bullet6.GetComponent<Image>().enabled = false;
			}

			if (currentAmmo > 6)
			{
				Bullet7.GetComponent<Image>().enabled = true;
			}

			else
			{
				Bullet7.GetComponent<Image>().enabled = false;
			}

			if (currentAmmo > 7)
			{
				Bullet8.GetComponent<Image>().enabled = true;
			}

			else
			{
				Bullet8.GetComponent<Image>().enabled = false;
			}
		}
	}
	private void HandleAiming()
    {
		//AIMING SECTION	
		if (Input.GetMouseButton(1) && !m_Animator.GetCurrentAnimatorStateInfo(1).IsName("IdleBandage") && shotgun.activeInHierarchy == true && !isSettingTrap)
		{
			m_Animator.SetBool("isAiming", true);
			isAiming = true;
			fLook.enabled = false;
			if (mainCamera != null)
			{
				Ray ray = mainCamera.ViewportPointToRay(Vector3.one * 0.5f);
				//Debug.DrawRay (ray.origin, ray.direction * maxDistance, Color.magenta, 2f);
				RaycastHit hit;

				if (Physics.Raycast(ray.origin, ray.direction, out hit, Mathf.Infinity, layerMask))
				{
					zombieHealth = hit.collider.GetComponentInParent<DemoEnemyControls>();
					crawlerControls = hit.collider.GetComponentInParent<CrawlerControls>();
					easterEgg = hit.collider.GetComponent<EasterEgg>();
					bool gasoline = hit.transform.gameObject.CompareTag("Gas");

					if (Physics.Raycast(ray.origin, ray.direction, out hit, Mathf.Infinity, obstacleMask)) //White Reticle If Obstacles
					{
						Reticle.SetActive(true);
						RedReticle.SetActive(false);
					}
					else if (zombieHealth != null || crawlerControls != null || easterEgg != null || gasoline)
					{ //Red Reticle If Available Target
						RedReticle.SetActive(true);
						Reticle.SetActive(false);
					}
				}
				else
				{ //White Reticle If Nothing
					Reticle.SetActive(true);
					RedReticle.SetActive(false);
				}
			}

		}

		else
		{
			m_Animator.SetBool("isAiming", false);
			isAiming = false;
			fLook.enabled = true;
			Reticle.SetActive(false);
			RedReticle.SetActive(false);

		}
	}
	private void HandleGunFire()
    {
		//GUN FIRE
		if (Input.GetMouseButtonDown(0) && m_Animator.GetBool("isAiming") == true && Time.time >= nextTimetoFire && !isReloading && shotgun.activeInHierarchy == true && !isSettingTrap)
		{
			if (currentAmmo >= 1)
			{
				nextTimetoFire = Time.time + 1f / fireRate;
				//StartCoroutine(Fire());
				StartCoroutine(Shoot());
			}
			else
			{
				MsgUI = FindObjectOfType(typeof(NotificationUI)) as NotificationUI;
				MsgUI.SendMsg("No Ammo! Press R to reload.");
				AudioClip clip = GunEmpty;
				weaponAudioSource.PlayOneShot(clip);
			}
		}
	}
	private void HandleStatsLock()
    {
		//STATS LOCK
		healthSlider.value = currentHealth;
		staminaSlider.value = currentStamina;
		flashlightSlider.value = currentFlashlight;

		if (currentHealth > Health)
		{
			currentHealth = Health;
		}

		if (currentStamina > Stamina)
		{
			currentStamina = Stamina;
		}

		if (currentHealth < minStamina)
		{
			currentStamina = minStamina;
		}

		//AMMO LOCK
		if (currentAmmo > maxAmmo)
		{
			currentAmmo = maxAmmo;
		}
	}
	private void HandleFlashlightPhysics()
    {
		//FLASHLIGHT DOUBLE WALKERS VISION
		if (LightOn)
		{
			currentHitObjects.Clear();
			RaycastHit[] hits = new RaycastHit[1];

			int numberOfHits = Physics.SphereCastNonAlloc(FlashlightPoint.transform.position, flashlightRadius, FlashlightPoint.transform.forward, hits, flashlightDistance, layerMask, QueryTriggerInteraction.UseGlobal);
			if (numberOfHits >= 1)
			{
				for (int i = 0; i < numberOfHits; i++)
				{
					currentHitObjects.Add(hits[i].transform.gameObject);
					currentHitDistance = hits[i].distance;

					foreach (GameObject zombie in currentHitObjects)
					{
						ai = hits[i].collider.GetComponentInParent<BreadcrumbAi.Ai>();
						if (ai != null)
						{
							ai.visionDistance = ai.visionDistance * 2f;
						}
					}

				}
			}
		}
	}
	private void HandleFlashlight()
    {
		//FLASHLIGHT TOGGLE
		if (Input.GetKeyDown(KeyCode.F) || DPadButtons.IsLeft)
		{
			toggleFlashlight();
			toggleFlashlightSFX();

			if (LightOn)
			{
				LightOn = false;
			}
			else if (!LightOn && flashlightSlider.value >= 0)
			{
				LightOn = true;
			}
		}

		//FLASHLIGHT CONTROL SECTION
		if (LightOn && flashlightSlider.value >= 0)
		{
			currentFlashlight -= Time.deltaTime / flashlightFallRate;
			LightSource.intensity = 5f;
		}
		if (LightOn && flashlightSlider.value <= 75)
		{
			LightSource.intensity = 4f;
		}
		if (LightOn && flashlightSlider.value <= 50)
		{
			LightSource.intensity = 3;
		}
		if (LightOn && flashlightSlider.value <= 25)
		{
			LightSource.intensity = 1.5f;
		}
		if (LightOn && flashlightSlider.value <= 0)
		{
			flashlightSlider.value = 0;
			LightSource.intensity = 0f;
			currentFlashlight = 0f;
		}

		else if (flashlightSlider.value >= maxFlashlight)
		{
			flashlightSlider.value = maxFlashlight;
		}
	}
	private void HandleStamina()
    {
		//SHOW&HIDE STAMINA SLIDER
		if (currentStamina < Stamina)
		{
			staminaSlider.gameObject.SetActive(true);
		}
		else
		{
			staminaSlider.gameObject.SetActive(false);
		}

		//STAMINA CONTROL SECTION
		bool _isRunning = IsRunning();
		bool _canRun = CanRun();

		if (_isRunning && _canRun)
		{
			currentStamina = Mathf.Clamp(currentStamina - (StaminaDecreasePerFrame * Time.deltaTime), 0.0f, Stamina);
			StaminaRegenTimer = 0.0f;
		}
		else
		{
			if (currentStamina < Stamina)
			{
				if (StaminaRegenTimer >= StaminaTimeToRegen)
					currentStamina = Mathf.Clamp(currentStamina + (StaminaIncreasePerFrame * Time.deltaTime), 0.0f, Stamina);
				else
					StaminaRegenTimer += Time.deltaTime;
			}
		}


		if (!_canRun)
		{
			StartCoroutine(StopRunMotion());
		}
		else
		{
			MotionControllerMotion walkOnlyMotion = mMotionController.GetMotion(0, "Walk Only Motion");
			walkOnlyMotion._IsEnabled = false;
		}
	}
	private void HandleFirstPerson()
    {
		//FIRST PERSON FEATURE
		if (Input.GetKeyDown(KeyCode.Tab))
		{
			if (!_1stPerson)
			{
				camRig.ActivateMotor(5);
				_1stPerson = true;

				motionController.SetAnimatorMotionPhase(0, 1130);
				motionController.ActivateMotion("Strafe", 0);
			}

			else if (_1stPerson)
			{
				camRig.ActivateMotor(6);
				_1stPerson = false;
			}
		}
	}
	IEnumerator StopRunMotion()
	{
		m_Animator.SetFloat("InputMagnitude", 0.5f, 0.1f, 0.5f);
		m_Animator.SetFloat("InputMagnitudeAvg", 0.5f, 1f, 0.5f);
		m_Animator.SetFloat("InputY", 0.5f, 1f, 0.5f);
		yield return new WaitForSeconds(0.1f);
		MotionControllerMotion walkOnlyMotion = mMotionController.GetMotion(0, "Walk Only Motion");
		walkOnlyMotion.IsEnabled = true;
	}
	public bool IsRunning()
	{
		if (Input.GetKey(KeyCode.LeftShift) && Input.GetKey(KeyCode.W))
		{
			return (true);
		}
		else
		{
			return (false);
		}
	}
	public bool CanRun()
	{
		if (currentStamina > 1f)
		{
			return (true);
		}
		else
		{
			return (false);
		}
	}
	/*IEnumerator Slide()
    {

		isSliding = true;
		AnimationClip slide = m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Slide");
		actorController.AddForce(actorController._Transform.forward * 10, m_Animator.GetCurrentAnimatorStateInfo(0).length);
		yield return new WaitForSeconds(1);
		Debug.Log("Sliding");
		
	}*/

	IEnumerator Knife()
	{

		isSliding = true;
		m_Animator.SetBool("isSliding", true);
		fLook.enabled = false;

		AudioClip clip = knifeSound;
		weaponAudioSource.PlayOneShot(clip);

		Collider[] hitEnemies = Physics.OverlapSphere(knifeHitPoint.position, knifeRadius, layerMask);

		foreach (Collider enemies in hitEnemies)
		{
			if (isSliding && enemies != null)
			{
				if (enemies.transform.tag == "Easter")
				{
					easterEgg = enemies.GetComponent<EasterEgg>();
					easterEgg.DestroyTrain();
					DestroyObject(enemies.transform.gameObject, 8);

				}

				if (enemies.transform.tag == "Body" || enemies.transform.tag == "Enemy")
				{
					zombieHealth = enemies.GetComponentInParent<DemoEnemyControls>();
					crawlerControls = enemies.GetComponentInParent<CrawlerControls>();
					if (zombieHealth != null || crawlerControls != null)
					{
						zombieHealth.GotHit(knifeDamage);
						crawlerControls.GotHit(knifeDamage);
						AudioClip hit = knifeHitSound;
						weaponAudioSource.PlayOneShot(hit);
					}
				}
			}
		}
		yield return new WaitForSeconds(1f);
		isSliding = false;
		m_Animator.SetBool("isSliding", false);

		//mMotionController.enabled = true;
		fLook.enabled = true;

	}

	public void KnifeHit()
	{
		/*RaycastHit hit;
		if (Physics.SphereCast(knifeHitPoint.transform.position, 4f, knifeHitPoint.transform.forward, out hit, 4f, layerMask, QueryTriggerInteraction.UseGlobal))
		{
			currentHitObject = hit.transform.gameObject;
			currentHitDistance = hit.distance;

			zombieHealth = hit.collider.GetComponentInParent<DemoEnemyControls>();
			easterEgg = hit.collider.GetComponent<EasterEgg>();

			if (hit.collider.transform.tag == "Easter")
			{
				easterEgg.DestroyTrain();
				DestroyObject(hit.transform.gameObject, 8);

			}

			if (zombieHealth != null)
			{
				if (hit.collider.transform.tag == "Body" || hit.collider.transform.tag == "Enemy")
				{
					zombieHealth.GotHit(damage);
				}
			}
		}
		else
		{
			currentHitDistance = maxDistance;
			currentHitObject = null;
		}*/
	}
	public IEnumerator CharacterSuicide()
	{
		if (isSuiciding)
		{
			float timeElapsed = 1f;
			float lerpDuration = 14;

			float startValue = 0;
			float endValue = 1.6f;

			fearSystem.currentFear = fearSystem.maxFear; //Keeping Anomaly FX

			//DISABLING CAM&INPUT
			camRig.enabled = false;
			camRig._IsCollisionsEnabled = false;
			InputSource.IsEnabled = false;
			fLook.enabled = false;
			if (_1stPerson)
			{
				camRig.ActivateMotor(6);
			}

			//DISABLING UI
			LightSource.enabled = false;
			QuestUI.SetActive(false);
			ShotgunUI.SetActive(false);
			GasolineUI.SetActive(false);
			PlayerVitalsUI.SetActive(false);
			Inventory.SetActive(false);
			KnifeUI.SetActive(false);

			//ON KNEE ANIMATION
			motionController.SetAnimatorMotionPhase(0, 3400, true);
			Player.tag = "Dead";
			m_Animator.SetBool("isSuiciding", true);
			isInjured = false; //Disabling Injured Sounds

			//STOP BLOOD
			m_Animator.SetBool("isInjured", false);
			BloodScreenFx.SetBool("50Health", false);
			BloodScreenFx.SetBool("100Health", true);

			yield return new WaitForSeconds(5f);

			//SUICIDE ANIMATION
			m_Animator.SetBool("isSuiciding2", true);
			yield return new WaitForSeconds(0.8f);

			//PLAY AUDIO
			audioSource.PlayOneShot(FireShot);
			audioSource.PlayOneShot(DeathTragicMusic);
			audioSource.PlayOneShot(headshotSound);
			if (HeartbeatAudioSource.isPlaying)
			{
				HeartbeatAudioSource.Stop();
			}

			//HEADSHOT&FALLING ANIMATION
			CharacterHead.SetActive(false);
			m_Animator.SetBool("isSuiciding3", true);

			//NEW BLOOD FX
			while (timeElapsed < lerpDuration)
			{
				camBlood.Blood_On_Screen = Mathf.Lerp(startValue, endValue, timeElapsed / lerpDuration);
				timeElapsed += Time.deltaTime;
				yield return null;
			}
			camBlood.Blood_On_Screen = endValue;

			//ENABLING GAMEOVER UI + DEATH MUSIC + HEARTBEAT STOP
			Gameover.SetActive(true);
			Cursor.visible = true;
			audioSource.clip = GameOverUIMusic;
			audioSource.Play();
			audioSource.loop = true;
			deathCount++;
		}
	}
	public IEnumerator CharacterDeath()
	{
		float timeElapsed = 1f;
		float lerpDuration = 14;

		float startValue = 0;
		float endValue = 1.6f;
		if (isDead)
		{
			//PLAY AUDIO
			audioSource.PlayOneShot(DeathSound);
			audioSource.PlayOneShot(DeathTragicMusic);

			//DISABLING CAM&INPUT
			camRig.enabled = false;
			camRig._IsCollisionsEnabled = false;
			InputSource.IsEnabled = false;
			fLook.enabled = false;

			if (_1stPerson)
			{
				camRig.ActivateMotor(6);
			}

			//DEATH ANIMATION
			motionController.SetAnimatorMotionPhase(0, 3375, true);
			Player.tag = "Dead";
			m_Animator.SetBool("isDead", true);

			//DISABLING UI
			LightSource.enabled = false;
			QuestUI.SetActive(false);
			ShotgunUI.SetActive(false);
			GasolineUI.SetActive(false);
			PlayerVitalsUI.SetActive(false);
			Inventory.SetActive(false);
			KnifeUI.SetActive(false);

			//STOP BLOOD
			m_Animator.SetBool("isInjured", false);
			BloodScreenFx.SetBool("50Health", false);
			BloodScreenFx.SetBool("100Health", true);

			//SEND ZOMBIES ANIMATION
			zombies = GameObject.FindGameObjectsWithTag("Enemy");
			closestZombie = null;
			foreach (GameObject zombie in zombies)
			{
				float curDistance;
				curDistance = Vector3.Distance(transform.position, zombie.transform.position);
				zombieHealth = zombie.gameObject.transform.GetComponent<DemoEnemyControls>();
				crawlerControls = zombie.gameObject.transform.GetComponent<CrawlerControls>();

				if (curDistance < 1f)
				{
					if (zombieHealth != null)
					{
						zombieHealth.EatPlayer();
						zombieHealth.transform.LookAt(transform);
						transform.LookAt(zombieHealth.transform);
					}

					if (crawlerControls != null)
					{
						crawlerControls.EatPlayer();
						crawlerControls.transform.LookAt(transform);
						transform.LookAt(crawlerControls.transform);
					}
				}

			}
			yield return closestZombie;

			//NEW BLOOD FX
			while (timeElapsed < lerpDuration)
			{
				camBlood.Blood_On_Screen = Mathf.Lerp(startValue, endValue, timeElapsed / lerpDuration);
				timeElapsed += Time.deltaTime;
				yield return null;
			}
			camBlood.Blood_On_Screen = endValue;

			//ENABLING GAMEOVER UI + DEATH MUSIC
			Gameover.SetActive(true);
			Cursor.visible = true;
			audioSource.clip = GameOverUIMusic;
			audioSource.Play();
			audioSource.loop = true;
			deathCount++;
			if (HeartbeatAudioSource.isPlaying)
			{
				HeartbeatAudioSource.Stop();
			}
		}
	}

	void SwitchState()
	{
		if (healthSlider.value <= 0 && !isDead)
		{
			isDead = true;
			beautify.sepiaIntensity = 1f;
			StartCoroutine(CharacterDeath());
		}

		else if (healthSlider.value > 0 && healthSlider.value < (Health / 5.5f))
		{
			beautify.sepiaIntensity = 1f;
			isInjured = true;
		}

		else if (healthSlider.value > (Health / 5.5f) && healthSlider.value < (Health / 4))
		{
			beautify.sepiaIntensity = 0.90f;
			isInjured = true;
		}

		else if (healthSlider.value > (Health / 4) && healthSlider.value < (Health / 2))
		{
			beautify.sepiaIntensity = 0.65f;
			isInjured = true;
		}

		else if (healthSlider.value > (Health / 2) && healthSlider.value < (Health / 1.3f))
		{
			beautify.sepiaIntensity = 0.35f;
			isInjured = false;
		}

		else if (healthSlider.value > (Health / 1.3f))
		{
			beautify.sepiaIntensity = 0f;
			isInjured = false;
		}

		if (isInjured && !isDead && !isSuiciding)
		{
			m_Animator.SetBool("isInjured", true);
			BloodScreenFx.SetBool("50Health", true);
			BloodScreenFx.SetBool("100Health", false);


			if (Time.time - timePainSoundPlayed < 4f) return;
			HeartbeatAudioSource.clip = Heartbeat;
			HeartbeatAudioSource.Play();
			int n = Random.Range(1, Painsounds.Length);
			AudioClip painSounds = Painsounds[n];
			if (!audioSource.isPlaying)
			{
				audioSource.PlayOneShot(painSounds);
				Painsounds[n] = Painsounds[0];
				Painsounds[0] = painSounds;
				timePainSoundPlayed = Time.time;
			}
		}

		if (!isInjured || isDead || isSuiciding)
		{
			m_Animator.SetBool("isInjured", false);
			BloodScreenFx.SetBool("50Health", false);
			BloodScreenFx.SetBool("100Health", true);

			HeartbeatAudioSource.clip = Heartbeat;
			HeartbeatAudioSource.Stop();
		}
	}

	IEnumerator ToggleCrouch()
	{
		for (int i = 0; i < m_Animator.layerCount; i++)
		{
			if (m_Animator.GetLayerName(i) == BaseLayer)
			{
				AnimatorStateInfo stateInfo = m_Animator.GetCurrentAnimatorStateInfo(i);

				if (stateInfo.IsName("Base Layer.Sneak v2-SM.Move Tree"))
				{
					isCrouching = true;
					stealthFX.SetBool("Stealth", true);
					yield return new WaitForSeconds(2);
				}


				if (stateInfo.IsName("Base Layer.WalkRunPivot v2-SM.Move Tree"))
				{
					isCrouching = false;
					stealthFX.SetBool("Stealth", false);
					yield return new WaitForSeconds(2);
				}
			}
		}
		yield return new WaitForSeconds(2);
	}
	public void Bleed(Quaternion rot)
	{
		GameObject blood = Instantiate(bloodPrefab, transform.position, rot) as GameObject;
		Destroy(blood, 5);
	}

	public void TakeDamage(float damage)
	{
		//PLAY PAIN SOUND
		int n = Random.Range(1, Hitsounds.Length);
		AudioClip clip = Hitsounds[n];
		audioSource.PlayOneShot(clip);

		//DAMAGE
		currentHealth -= damage;

		//StartCoroutine(HitAnimation());

	}

	public void OnTriggerStay(Collider other)
	{
		if (other.gameObject.CompareTag("Fire"))
		{
			currentHealth -= Time.deltaTime / 3;
			if (!audioSource.isPlaying)
			{
				AudioClip clip = FrySound;
				audioSource.PlayOneShot(clip);
			}
		}
	}

	public void OnTriggerEnter(Collider other)
	{
		/*if (isSliding && other != null)
		{
			Debug.Log("Knife Damage");
			Debug.Log(other.name);
			if (other.transform.tag == "Easter")
			{
			easterEgg = other.GetComponent<EasterEgg>();
				easterEgg.DestroyTrain();
				DestroyObject(other.transform.gameObject, 8);

			}

				if (other.transform.tag == "Body" || other.transform.tag == "Enemy")
			{
			zombieHealth = other.GetComponentInParent<DemoEnemyControls>();
			if (zombieHealth != null)
				{
					zombieHealth.GotHit(knifeDamage);
					Debug.Log(knifeDamage);
				}
			}
		}*/
	}

	/*private IEnumerator HitAnimation()
    {
		//GET NEARBY ZOMBIE THAT ATTACKS
		zombies = GameObject.FindGameObjectsWithTag("Enemy");

		foreach (GameObject zombie in zombies)
		{
			float curDistance;
			curDistance = Vector3.Distance(transform.position, zombie.transform.position);

			// Determine which direction to rotate towards
			Vector3 targetPosition = zombie.transform.position;
			Vector3 targetDirection = transform.position - zombie.transform.position;
			Quaternion desiredRotation = Quaternion.LookRotation(targetDirection, transform.up);

			//IF ONE IS NEAR
			if (curDistance < 1f)
			{
				//LOOK AT THIS ZOMBIE
				Debug.Log("OUCH");
                Debug.DrawRay(transform.position, targetPosition * maxDistance, Color.blue, 2f);
                zombie.transform.LookAt(transform);
				transform.LookAt(targetPosition, transform.up);

                //DISABLING CAM&INPUT
                camRig.enabled = false;
				camRig._IsCollisionsEnabled = false;
				InputSource.IsEnabled = false;
				fLook.enabled = false;

				yield return new WaitForSeconds(1.5f);

				//ENABLING CAM&INPUT
				camRig.enabled = true;
				camRig._IsCollisionsEnabled = true;
				InputSource.IsEnabled = true;
				fLook.enabled = true;
			}
		}
	}*/
	void toggleFlashlight()
	{
		if (LightOn)
		{
			LightSource.enabled = false;
		}
		else
		{
			LightSource.enabled = true;
		}
	}
	void toggleFlashlightSFX()
	{
		if (LightSource.enabled)
		{
			audioSource.clip = TurnOn;
			audioSource.Play();
		}
		else
		{
			audioSource.clip = TurnOff;
			audioSource.Play();
		}

	}

	private IEnumerator CheckGasoline()
	{
		//Toggle UI If Gas In Inventory
		for (int i = 0; i < InvManager.MaxItems; i++)
		{
			if (InvManager.Slots[i].IsTaken == true) //Checking if there's an item in this slot.
			{
				Item ItemScript = InvManager.Slots[i].Item.GetComponent<Item>(); //Getting the item script from the items inside the bag.
																				 //ItemScript.Name = PlayerPrefs.GetString("Name" + i.ToString()); //Loading the item's name.
				if (ItemScript.Name == "Gasoline" && !isDead) //Checking if the type of the new item matches with another item already in the bag.
				{
					GasolineUI.SetActive(true);
					gasolineSlider.value = ItemScript.AmountPercent;

					if (gasolineSlider.value <= 0)
					{
						gasolineSlider.value = 0;
					}

					if (gasolineSlider.value >= ItemScript.AmountPercent)
					{
						gasolineSlider.value = ItemScript.AmountPercent;
					}

					if (Input.GetKeyDown(KeyCode.Q) && ItemScript.AmountPercent >= 20 && !isAiming && !isReloading)
					{
						ItemScript.AmountPercent -= 20;
						StartCoroutine(SetTrap());
					}
				}

				else
				{
					GasolineUI.SetActive(false);
				}
			}
		}
		yield return new WaitForSeconds(1);
	}

	private IEnumerator SetTrap()
	{
		isSettingTrap = true;

		AudioClip clip = GasolineSound;
		audioSource.PlayOneShot(clip);

		shotgun.SetActive(false);
		GasCan.SetActive(true);

		m_Animator.SetBool("isSettingTrap", true);
		yield return new WaitForSeconds(0.01f);
		m_Animator.SetBool("isSettingTrap", false);

		mMotionController.enabled = false;
		camRig.EnableMotor<TransitionMotor>(false, "Targeting");
		camRig.EnableMotor<TransitionMotor>(false, "Targeting In");
		camRig.EnableMotor<TransitionMotor>(false, "Targeting Out");

		GameObject gas = Instantiate(gasolineTrap, transform.position + transform.forward, Quaternion.Euler(-90, 0, 0)) as GameObject;

		yield return new WaitForSeconds(4);
		mMotionController.enabled = true;
		camRig.EnableMotor<TransitionMotor>(true, "Targeting");
		camRig.EnableMotor<TransitionMotor>(true, "Targeting In");
		camRig.EnableMotor<TransitionMotor>(true, "Targeting Out");
		shotgun.SetActive(true);
		GasCan.SetActive(false);

		isSettingTrap = false;
	}
	private IEnumerator Fire()
	{
		//Debug.DrawRay(firePoint.transform.position, firePoint.transform.forward * 12, Color.red, 2f);
		//currentHitDistance = maxDistance;
		//currentHitObjects.Clear();
		//RaycastHit[] hits = new RaycastHit[1];

		Ray ray = Camera.main.ViewportPointToRay(Vector3.one * 0.5f);
		Debug.DrawRay(ray.origin, ray.direction * maxDistance, Color.green, 2f);
		RaycastHit hit;
		//if (Physics.SphereCast(firePoint.transform.position, sphereRadius, firePoint.transform.forward, out hit, maxDistance, layerMask, QueryTriggerInteraction.UseGlobal))
		//if (Physics.SphereCast(ray.origin, sphereRadius, ray.direction, out hit, maxDistance, layerMask, QueryTriggerInteraction.UseGlobal))
		//if (!Physics.Raycast(ray.origin, ray.direction, out hit, maxDistance, obstacleMask, QueryTriggerInteraction.UseGlobal)) //Fix to hide enemies behind obstacles

		if (Physics.Raycast(ray.origin, ray.direction, out hit, maxDistance, layerMask, QueryTriggerInteraction.UseGlobal))
		//int numberOfHits = Physics.SphereCastNonAlloc(firePoint.position, sphereRadius, firePoint.transform.forward, hits, maxDistance, layerMask, QueryTriggerInteraction.UseGlobal);
		//for (int i = 0; i < numberOfHits; i++)
		{
			//currentHitObjects.Add(hits[i].transform.gameObject);
			//currentHitDistance = hits[i].distance;
			currentHitObject = hit.transform.gameObject;
			currentHitDistance = hit.distance;

			//zombieHealth = hits[i].collider.GetComponentInParent<DemoEnemyControls>();
			zombieHealth = hit.collider.GetComponentInParent<DemoEnemyControls>();
			crawlerControls = hit.collider.GetComponentInParent<CrawlerControls>();
			spreadFire = hit.collider.GetComponent<SpreadFire>();
			easterEgg = hit.collider.GetComponent<EasterEgg>();

			if (hit.collider.transform.tag == "Gas")
			{
				spreadFire.SetFire();
				DestroyObject(hit.transform.gameObject, 3);

			}

			if (hit.collider.transform.tag == "Easter")
			{
				trainDestroyed++;
				easterEgg.DestroyTrain();
				DestroyObject(hit.transform.gameObject, 8);

			}


			//if (hits[i].collider.transform.tag == "Head")
			if (hit.collider.transform.tag == "Head")
			{
				if (zombieHealth != null)
				{
					zombieHealth.HeadShot(headshotDamage);
				}
				else if (crawlerControls != null)
				{
					crawlerControls.HeadShot(headshotDamage);
				}
			}


			//else if (hits[i].collider.transform.tag == "Body" || hits[i].collider.transform.tag == "Enemy")
			else if (hit.collider.transform.tag == "Body" || hit.collider.transform.tag == "Enemy")
			{
				if (zombieHealth != null)
				{
					zombieHealth.GotHit(damage);
				}
				else if (crawlerControls != null)
				{
					crawlerControls.GotHit(damage);
				}
			}
		}


		else
		{
			currentHitDistance = maxDistance;
			currentHitObject = null;
		}

		m_Animator.SetBool("isFire", true);
		MotionControllerMotion fire = mMotionController.GetMotion(1, "Fire");
		mMotionController.ActivateMotion(fire);
		AudioClip clip = FireShot;
		weaponAudioSource.PlayOneShot(clip);
		muzzleFlash.Play();
		muzzleLight.SetActive(true);
		yield return new WaitForSeconds(0.1f);
		muzzleLight.SetActive(false);
		currentAmmo--;

		CameraShake.Shake(0.25f, 0.08f);

		AmmoText.GetComponent<Text>().text = currentAmmo.ToString() + " / 5";

		if (currentAmmo > 0) {
			Bullet1.GetComponent<Image>().enabled = true;
		} else
		{
			Bullet1.GetComponent<Image>().enabled = false;
		}

		if (currentAmmo > 1) {
			Bullet2.GetComponent<Image>().enabled = true;
		} else
		{
			Bullet2.GetComponent<Image>().enabled = false;
		}

		if (currentAmmo > 2) {
			Bullet3.GetComponent<Image>().enabled = true;
		} else
		{
			Bullet3.GetComponent<Image>().enabled = false;
		}

		if (currentAmmo > 3) {
			Bullet4.GetComponent<Image>().enabled = true;
		} else
		{
			Bullet4.GetComponent<Image>().enabled = false;
		}

		if (currentAmmo > 4) {
			Bullet5.GetComponent<Image>().enabled = true;
		} else
		{
			Bullet5.GetComponent<Image>().enabled = false;
		}

		yield return new WaitForSeconds(1 - .25f);
		m_Animator.SetBool("isFire", false);
		yield return new WaitForSeconds(2);
	}

	private IEnumerator Shoot()
	{
		if (menuScript1.PlayerSelected == 2 || menuScript1.PlayerSelected == 3)
		{
				/*GameObject bullet = GameObject.Instantiate(bulletProjectile, firePoint.position, Quaternion.identity, bulletParent);
				BulletController bulletController = bullet.GetComponent<BulletController>();*/

            GameObject pooledBullet = ObjectPool.instance.GetPooledObjects();
            if (pooledBullet == null)
            {
                yield break;
            }

            BulletController bulletController = pooledBullet.GetComponent<BulletController>();

            RaycastHit hit;
				if (Physics.Raycast(mainCamera.transform.position, mainCamera.transform.forward, out hit, Mathf.Infinity, aimLayerMask))
				{
                //debugTransform.position = hit.point;

                //bulletController.target = hit.point;
                //bulletController.hit = true;

                bulletController.target = hit.point;
                bulletController.hit = true;
                pooledBullet.transform.position = firePoint.position;
                pooledBullet.transform.LookAt(mainCamera.transform.forward);
                pooledBullet.SetActive(true);

            }

				else
				{
                //debugTransform.position = hit.point;

                //bulletController.target = mainCamera.transform.position + mainCamera.transform.forward * 25f;
                //bulletController.hit = false;

                bulletController.target = mainCamera.transform.position + mainCamera.transform.forward * 25f;
                bulletController.hit = false;
                pooledBullet.transform.position = firePoint.position;
                pooledBullet.transform.LookAt(mainCamera.transform.forward);
                pooledBullet.SetActive(true);
            }

                m_Animator.SetBool("isFire", true);
                MotionControllerMotion fire = mMotionController.GetMotion(1, "Fire");
                mMotionController.ActivateMotion(fire);
                AudioClip clip = FireShot;
                weaponAudioSource.PlayOneShot(clip);
                muzzleFlash.Play();
                muzzleLight.SetActive(true);
                yield return new WaitForSeconds(0.1f);
                muzzleLight.SetActive(false);
                currentAmmo--;

                CameraShake.Shake(0.25f, 0.08f);

                AmmoText.GetComponent<Text>().text = currentAmmo.ToString() + " / 5";

                if (currentAmmo > 0)
                {
                    Bullet1.GetComponent<Image>().enabled = true;
                }
                else
                {
                    Bullet1.GetComponent<Image>().enabled = false;
                }

                if (currentAmmo > 1)
                {
                    Bullet2.GetComponent<Image>().enabled = true;
                }
                else
                {
                    Bullet2.GetComponent<Image>().enabled = false;
                }

                if (currentAmmo > 2)
                {
                    Bullet3.GetComponent<Image>().enabled = true;
                }
                else
                {
                    Bullet3.GetComponent<Image>().enabled = false;
                }

                if (currentAmmo > 3)
                {
                    Bullet4.GetComponent<Image>().enabled = true;
                }
                else
                {
                    Bullet4.GetComponent<Image>().enabled = false;
                }

                if (currentAmmo > 4)
                {
                    Bullet5.GetComponent<Image>().enabled = true;
                }
                else
                {
                    Bullet5.GetComponent<Image>().enabled = false;
                }

                yield return new WaitForSeconds(1 - .25f);
                m_Animator.SetBool("isFire", false);
                yield return new WaitForSeconds(2);
		}

		else if (menuScript1.PlayerSelected == 0 || menuScript1.PlayerSelected == 1) // IF ARTHUR
		{
			for (int i = 0; i < bulletPerShot; i++)
			{
				Vector3 shootDirection = mainCamera.transform.forward;
				shootDirection.x += Random.Range(-inaccuracyDistance * 2, inaccuracyDistance * 2);
                shootDirection.y += Random.Range(-inaccuracyDistance, inaccuracyDistance);


				GameObject pooledBullet = ObjectPool.instance.GetPooledObjects();
				if (pooledBullet == null)
				{
					yield break;
				}

				BulletController bulletController = pooledBullet.GetComponent<BulletController>();

				RaycastHit hit;
				if (Physics.Raycast(mainCamera.transform.position, shootDirection, out hit, Mathf.Infinity, aimLayerMask))
				{
					//debugTransform.position = hit.point;
                    bulletController.target = hit.point;
					bulletController.hit = true;
					pooledBullet.transform.position = firePoint.position;
					pooledBullet.transform.LookAt(shootDirection);
					pooledBullet.SetActive(true);
                }

				else
				{
					//debugTransform.position = hit.point;
					bulletController.target = mainCamera.transform.position + shootDirection;
                    bulletController.hit = false;
                    pooledBullet.transform.position = firePoint.position;
                    pooledBullet.transform.LookAt(shootDirection);
                    pooledBullet.SetActive(true);
                }

			}

            m_Animator.SetBool("isFire", true);
            MotionControllerMotion fire = mMotionController.GetMotion(1, "Fire");
            mMotionController.ActivateMotion(fire);
            AudioClip clip = FireShot;
            weaponAudioSource.PlayOneShot(clip);
            muzzleFlash.Play();
            muzzleLight.SetActive(true);
            yield return new WaitForSeconds(0.1f);
            muzzleLight.SetActive(false);
            currentAmmo--;

            CameraShake.Shake(0.25f, 0.08f);

            AmmoText.GetComponent<Text>().text = currentAmmo.ToString() + " / 5";

            if (currentAmmo > 0)
            {
                Bullet1.GetComponent<Image>().enabled = true;
            }
            else
            {
                Bullet1.GetComponent<Image>().enabled = false;
            }

            if (currentAmmo > 1)
            {
                Bullet2.GetComponent<Image>().enabled = true;
            }
            else
            {
                Bullet2.GetComponent<Image>().enabled = false;
            }

            if (currentAmmo > 2)
            {
                Bullet3.GetComponent<Image>().enabled = true;
            }
            else
            {
                Bullet3.GetComponent<Image>().enabled = false;
            }

            if (currentAmmo > 3)
            {
                Bullet4.GetComponent<Image>().enabled = true;
            }
            else
            {
                Bullet4.GetComponent<Image>().enabled = false;
            }

            if (currentAmmo > 4)
            {
                Bullet5.GetComponent<Image>().enabled = true;
            }
            else
            {
                Bullet5.GetComponent<Image>().enabled = false;
            }

            yield return new WaitForSeconds(1 - .25f);
            m_Animator.SetBool("isFire", false);
            yield return new WaitForSeconds(2);
        }
	}
	
	Vector3 GetShootingDirection()
	{
		Vector3 targetPos = Camera.main.transform.position + Camera.main.transform.forward * Mathf.Infinity;
		targetPos = new Vector3(
			targetPos.x = Random.Range(-inaccuracyDistance, inaccuracyDistance),
            targetPos.y = Random.Range(-inaccuracyDistance, inaccuracyDistance),
            targetPos.z = Random.Range(-inaccuracyDistance, inaccuracyDistance)
            );
		direction = targetPos - Camera.main.transform.position;
		return direction.normalized;
	}
	private IEnumerator Reload()
	{
		for (int i = 0; i < InvManager.MaxItems; i++)
		{
			if (InvManager.Slots[i].IsTaken == true) //Checking if there's an item in this slot.
			{
				Item ItemScript = InvManager.Slots[i].Item.GetComponent<Item>(); //Getting the item script from the items inside the bag.
																				 //ItemScript.Name = PlayerPrefs.GetString("Name" + i.ToString()); //Loading the item's name.
				if (ItemScript.Name == "Ammunition" && ItemScript.Amount >= 1) //Checking if the type of the new item matches with another item already in the bag.
				{
					isReloading = true;
					m_Animator.SetBool("isReloading", true);
					MotionControllerMotion reload = mMotionController.GetMotion(1, "Reload");
					mMotionController.ActivateMotion(reload);

					int ammoToRemove = (maxAmmo - currentAmmo);
					if (ammoToRemove > ItemScript.Amount)
					{
						ammoToRemove = ItemScript.Amount;
					}

					InvManager.RemoveItem(InvManager.Slots[i].Item, (maxAmmo - currentAmmo));

					for (int b = 0; b < ammoToRemove; b++)
                    {
						weaponAudioSource.PlayOneShot(BulletReloadSound);
						currentAmmo++;
						yield return new WaitForSeconds(reloadtime);

						if (currentAmmo == maxAmmo)
                        {
							AudioClip clip = ReloadSound;
							weaponAudioSource.PlayOneShot(clip);
							m_Animator.SetBool("isReloading", false);
							isReloading = false;
						}
					}

					m_Animator.SetBool("isReloading", false);
					isReloading = false;

				}
			}
		}
	}

	public IEnumerator ActivateGlowStick()
    {
		GlowStick.SetActive(true);
		GlowStickON = true;
		yield return new WaitForSeconds(30);
		GlowStick.SetActive(false);
		GlowStickON = false;
	}
		
	private void OnDrawGizmosSelected()
	{
		Gizmos.color = Color.yellow;
		if (knifeHitPoint == null)
			return;
		//Debug.DrawLine(FlashlightPoint.transform.position, FlashlightPoint.transform.position + FlashlightPoint.transform.forward * currentHitDistance);
		//Gizmos.DrawWireSphere(FlashlightPoint.transform.position + FlashlightPoint.transform.forward * currentHitDistance, flashlightRadius);
		Gizmos.DrawWireSphere(knifeHitPoint.transform.position, knifeRadius);
	}

	public void LoadData(GameData data)
	{
		this.currentHealth = data.health;
		this.currentStamina = data.stamina;
		this.currentFlashlight = data.flashlightAmount;
		this.currentAmmo = data.ammo;
		this.trainDestroyed = data.trainDestroyed;
		this.deathCount = data.deathCount;
		this.fatalHeadShot= data.fatalHeadShot;
		this.transform.position = data.playerPosition;

    }

    public void SaveData(GameData data)
    {
        data.health = this.currentHealth;
		data.stamina = this.currentStamina;
		data.flashlightAmount = this.currentFlashlight;
		data.ammo = this.currentAmmo;
		data.trainDestroyed = this.trainDestroyed;
		data.deathCount= this.deathCount;
		data.fatalHeadShot= this.fatalHeadShot;
		data.playerPosition = this.transform.position;

    }
}