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

public class Penguin_script : MonoBehaviour {
	private Rigidbody2D rb;
	private Vector3 target;
	public float forceAmount = 10;
	public float max_velocity = .25f;
	public float noMoveRadius = .03f;
	private SpriteRenderer sprite;
	private Animator animator;
	private bool arrived;

	void Start() {
		rb = GetComponent<Rigidbody2D>();
		sprite = GetComponent<SpriteRenderer>();
		animator = GetComponent<Animator>();
		arrived = false;
	}

	void Update() {
		if (!arrived) {
			Debug.Log(arrived);
			// Move penguins where the mouse is
			target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
			target.z = 0;

			if (Mathf.Abs((target - transform.position).magnitude) > noMoveRadius) {
				rb.AddForce((target - transform.position).normalized * forceAmount);
			}
			else {
				rb.velocity = Vector3.zero;
				rb.angularVelocity = 0;
			}

			if (rb.velocity.magnitude > max_velocity)
				rb.velocity = rb.velocity.normalized * max_velocity + (new Vector2(Random.Range(-.5f, .5f), Random.Range(-.5f, .5f)));

			//Flip the sprite when he goes left
			float h_velocity = target.x - transform.position.x;
			float v_velocity = target.y - transform.position.y;

			if (h_velocity < 0 ^ v_velocity < 0)
				sprite.flipX = true;
			else
				sprite.flipX = false;

			// Tell animation player y velocity
			animator.SetFloat("Velocity_y", v_velocity);
		}
	}

	public void Arrive() {
		rb.velocity = Vector2.zero;
		rb.angularDrag = 0;
		
		animator.SetBool("Arrived", true);
		arrived = true;
		max_velocity = 0 ;
	}
}