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

public class SimpleMovement : MonoBehaviour {

	public float moveSpeed = 1.0f;
	public float lookSpeed = 1.0f;
	public float colDistance = 1.0f;

	public float maxDistance = 900f;

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		if(!GlobalScript.controlEnabled || GlobalScript.orbiting)
			return;

		Vector3 newpos = transform.position;
		Vector3 right = transform.right * Input.GetAxis("Horizontal") * moveSpeed;
		newpos += right;
		Vector3 forward = transform.forward * Input.GetAxis("Vertical") * moveSpeed;
		newpos += forward;

		if((newpos - transform.position).magnitude > .0001f && newpos.magnitude < maxDistance){
			Collider[] cols = Physics.OverlapSphere(newpos, colDistance, 1 << LayerMask.NameToLayer("Obstacle"));
			if(cols.Length == 0){//Raycast(transform.position, newpos - transform.position, colDistance)){
				transform.position = newpos;
			}else{
				foreach(Collider c in cols){
					c.gameObject.SendMessage("Collide", this.transform, SendMessageOptions.DontRequireReceiver);
				}

				newpos = transform.position + right;
				if(Physics.OverlapSphere(newpos, colDistance, 1 << LayerMask.NameToLayer("Obstacle")).Length == 0){
					transform.position = newpos;
				}else{
					newpos = transform.position + forward;
					if(Physics.OverlapSphere(newpos, colDistance, 1 << LayerMask.NameToLayer("Obstacle")).Length == 0){
						transform.position = newpos;
					}
				}

			}
		}
		transform.Rotate(0f, Input.GetAxis("Mouse X") * lookSpeed, 0f);
	}
}
