using UnityEngine;
using System.Collections;

public class Movement : MonoBehaviour {

	public float speed = 20f;
	public float jumpForce = 20f;
	public bool canJump = true;
	public int playerNum = 0;

	//public float current_z = 40.0f;

	float x = 0f;
	float y = 0f;
	Vector3 last_angle = Vector3.zero;

	static bool askedtoreload = false;

	// Use this for initialization
	void Start () {
		askedtoreload = false;
	}
	
	// Update is called once per frame
	void Update () {
	}

	void FixedUpdate(){
		Vector3 movementDir = new Vector3(Input.GetAxis("P" + playerNum + "MoveH"),0f,Input.GetAxis("P" + playerNum + "MoveV")).normalized;
		rigidbody.AddForce(movementDir*speed);
		if(Input.GetButton("P" + playerNum + "Jump") && canJump){
			rigidbody.AddForce(transform.up*jumpForce,ForceMode.Impulse);
			canJump = false;
		}

		x = Input.GetAxis("P" + playerNum + "LookH");
		y = Input.GetAxis("P" + playerNum + "LookV");

		if(x != 0 || y != 0) 
			transform.eulerAngles = new Vector3(transform.eulerAngles.x, Mathf.Atan2(-x, -y) * Mathf.Rad2Deg, transform.eulerAngles.z);

		if(transform.position.y < -40f)
		{
			if(!askedtoreload)
			{
				Debug.Log("DEATH, restart level");

				if(GameObject.FindObjectOfType<SplashScreen>().currentLevel == 3){
					ArenaScript.registerDeath(playerNum);
				}

				GameObject.FindObjectOfType<SplashScreen>().Reload();
				askedtoreload = true;
			}
		}
		
	}

	void OnCollisionEnter(Collision other){
		if(other.gameObject.CompareTag("Ground")){
			canJump = true;
		}
	}

	static float ClampAngle(float angle){
		if(angle < -360)
			angle+=360;
		if(angle > 360)
			angle -= 360;
		return Mathf.Clamp(angle, -360, 360);
	}
}
