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

public class Enemy_SnakeScript : MonoBehaviour {

	GameObject playerObject;
	Transform playerPosition;
	Vector3 homePosition;
	Rigidbody2D ownBod;

	public float strikingDistance = 8.0f;
	public float leashDistance = 1.7f;
	public float pullback = 0.5f;  // Percent distance snake rebounds to when reaching maximum distance

	// Use this for initialization
	void Start () {

		playerObject = GameObject.FindGameObjectWithTag ("Player");
		playerPosition = playerObject.GetComponent<Transform> ();
		ownBod = gameObject.GetComponent<Rigidbody2D> ();
		homePosition = transform.position;
		
	}
	
	// Update is called once per frame
	void FixedUpdate () {

		if (Mathf.Abs (Vector2.Distance (playerPosition.position, transform.position))
		    < strikingDistance) {

			//ownBod.gravityScale = 1;
			ownBod.AddForce ((transform.position - playerPosition.position) * -50);

		} else {
			gameObject.GetComponent<Rigidbody2D> ().velocity *= 0;
			transform.position = transform.position * pullback + homePosition * (1.0f - pullback);
		}

		// Leashing Behavior
		if (Mathf.Abs (Vector2.Distance (homePosition, transform.position)) > leashDistance)
		{
			transform.position = transform.position * pullback + homePosition * (1.0f - pullback);
			gameObject.GetComponent<Rigidbody2D>().velocity *= 0.2f;
		}

	}

	void OnCollisionEnter2D(Collision2D other)
	{
		if (other.gameObject.tag == "Player") {
			Rigidbody2D ownBod = gameObject.GetComponent<Rigidbody2D> ();

			ownBod.bodyType = RigidbodyType2D.Kinematic;
			ownBod.velocity *= 0;
		}

	}
}
