﻿using UnityEngine;
using System.Collections;

/// <summary>
/// Player movement behavior
/// </summary>
public class PlayerMove : MonoBehaviour
{
	/// <summary>
	///  Target Rigidbody2D
	/// </summary>
	[SerializeField]
	private Rigidbody2D _Target = null;

	/// <summary>
	/// Speed of movement
	/// </summary>
	[SerializeField]
	private float _Speed = 0f;

	/// <summary>
	/// Horizontal input axis name
	/// </summary>
	[SerializeField]
	private string _XAxisName = "Horizontal";

	/// <summary>
	/// Vertical input axis name
	/// </summary>
	[SerializeField]
	private string _YAxisName = "Vertical";

	private Vector2 _Velocity = Vector2.zero;

	void Awake()
	{
		// If _Target is null, do GetComponent.
		if (_Target == null)
		{
			_Target = GetComponent<Rigidbody2D>();
		}
	}

	/// <summary>
	/// Player movement
	/// </summary>
	/// <param name="velocity">Moving speed vector</param>
	void Move(Vector2 velocity)
	{
		if (_Target == null)
		{
			return;
		}

		// Get world coordinates of bottom left of screen from viewport
		Vector2 min = Camera.main.ViewportToWorldPoint(new Vector2(0, 0));

		// Get the world coordinates of the upper right corner of the screen from the viewport
		Vector2 max = Camera.main.ViewportToWorldPoint(new Vector2(1, 1));

		// Get player position
		Vector2 pos = _Target.position;

		// Add movement
		pos += velocity * Time.deltaTime;

		// Restrict the player's position so that it fits within the screen
		pos.x = Mathf.Clamp(pos.x, min.x, max.x);
		pos.y = Mathf.Clamp(pos.y, min.y, max.y);

		// Move the player's position.
		_Target.MovePosition( pos );
	}

	void Update ()
	{
		// Get input
		float x = Input.GetAxisRaw(_XAxisName);
		float y = Input.GetAxisRaw(_YAxisName);

		// Calculate the input value to the velocity vector.
		_Velocity = new Vector2(x, y).normalized * _Speed;
	}

	void FixedUpdate()
	{
		Move(_Velocity);
	}
}
