using UnityEngine;
using System.Collections;

public class DPad2 : MonoBehaviour {

	public GUITexture up;
	public GUITexture down;
	public GUITexture left;
	public GUITexture right;
	//public GUITexture fire;
	
	public Transform controlObject;
	
	
	// Use this for initialization
	void Start () {
	
	}
	
	void OnEnable(){
		Gesture.onMouse1E += Pressed;
		Gesture.onTouchE += Pressed;
	}
	
	void OnDisable(){
		Gesture.onMouse1E -= Pressed;
		Gesture.onTouchE -= Pressed;
	}
/*	
	// Update is called once per frame
	void Update () {
		
		
		//limit the position of the control object
		float x=controlObject.position.x;
		float z=controlObject.position.z;
		
		//x=Mathf.Clamp(x, -5, 5);
		//z=Mathf.Clamp(z, -5, 5);
		
		controlObject.position=new Vector3(x, controlObject.position.y, z);
	}
	*/
	
	//call when the screen is touched/clicked
	void Pressed(Vector2 pos){
		
		//set a zero vector
		Vector3 moveDir=Vector3.zero;
		Vector3 fwd = transform.forward * 0;
		
		Vector3 eulerAngleVelocity = new Vector3(0, 0, 0);
		
		//if any of the button is pressed, set the corresponding  move direction
		if(up.HitTest(pos)){
			fwd = transform.forward * -15000;
			//moveDir+=new Vector3(0, 0, 1);
		}
		if(down.HitTest(pos)){
			fwd = transform.forward * 15000;
			//moveDir+=new Vector3(0, 0, -1);
		}
		if(left.HitTest(pos)){
			//Input.GetAxis("Horizontal") = Input.GetAxis("Horizontal") -0.1;
			eulerAngleVelocity = new Vector3(0, -100, 0);
			//moveDir+=new Vector3(-1, 0, 0);
		}
		if(right.HitTest(pos)){
			//Input.GetAxis("Horizontal") = Input.GetAxis("Horizontal") +0.1;
			eulerAngleVelocity = new Vector3(0, 100, 0);
			//moveDir+=new Vector3(1, 0, 0);
		}
		//if(fire.HitTest(pos)){ }
		
		
		//normalized the total moveDir
		moveDir=moveDir.normalized;
		
		//move the controlObject according to the input move direction
		controlObject.rigidbody.AddForce(fwd);
		//controlObject.Translate(moveDir*Time.deltaTime*3);
		//Quaternion target = Quaternion.Euler(tiltAroundX, tiltAroundY, tiltAroundZ);
        //transform.rotation = Quaternion.Slerp(transform.rotation, target, Time.deltaTime * smooth);
		
		Quaternion deltaRotation = Quaternion.Euler(eulerAngleVelocity * Time.deltaTime);
        rigidbody.MoveRotation(rigidbody.rotation * deltaRotation);
		//transform.rigidbody.MoveRotation
	}
	
	
	void OnGUI(){
		if(GUI.Button(new Rect(10, 10, 130, 35), "Back to Menu")){
			Application.LoadLevel("Menu");
		}
	
}
}
