// Basado en el script otiginal de rojasasa.
// Publicado originalmente en el hilo "Mira Dinamica" del foro UnitySpain.com

var ColorNormal : Color = Color.black;
var ColorActivo : Color = Color.red;
var DetectLayers : String[];
var VisibilityDist : float = 100;
var size : float = 8;
var minimo : float = 16;
var maximo : float = 64;
var rateSize : float = 0.3;

private var TexturaNormal : Texture2D;
private var TexturaActiva : Texture2D;
private var intervalo : float;
private var controller : CharacterController;

function Start(){
	controller = gameObject.GetComponent(CharacterController);
	TexturaNormal = new Texture2D(1, 1);
	TexturaNormal.SetPixel (0, 0, ColorNormal);
	TexturaNormal.Apply();
	TexturaActiva = new Texture2D(1, 1);
	TexturaActiva.SetPixel (0, 0, ColorActivo);
	TexturaActiva.Apply();
}

function OnGUI (){
	var IsActive : boolean = false;
	
	if(controller.isGrounded)
		intervalo = controller.velocity.magnitude / rateSize;
	else
		intervalo = maximo;
	intervalo = Mathf.Clamp(intervalo, minimo, maximo);
	
	var hit : RaycastHit;
	var fwd : Vector3 = Camera.main.transform.TransformDirection(Vector3.forward);
	var layerMask : int = 1 << 9;
	layerMask = ~layerMask;
	
	
    if (Physics.Raycast (Camera.main.transform.position, fwd, hit, VisibilityDist, layerMask)){
		for(var MyTag : String in DetectLayers){
			if(hit.transform.tag == MyTag)
				IsActive = true;
		}
	}
	
	if(IsActive){
		GUI.DrawTexture (Rect(Screen.width/2 - size/2 - intervalo, Screen.height/2 - size/8, size, size/4), TexturaActiva);
		GUI.DrawTexture (Rect(Screen.width/2 - size/2 + intervalo, Screen.height/2 - size/8, size, size/4), TexturaActiva);
		GUI.DrawTexture (Rect(Screen.width/2 - size/8, Screen.height/2 - size/2 - intervalo, size/4, size), TexturaActiva);
		GUI.DrawTexture (Rect(Screen.width/2 - size/8, Screen.height/2 - size/2 + intervalo, size/4, size), TexturaActiva);
	}
	else{
		GUI.DrawTexture (Rect(Screen.width/2 - size/2 - intervalo, Screen.height/2 - size/8, size, size/4), TexturaNormal);
		GUI.DrawTexture (Rect(Screen.width/2 - size/2 + intervalo, Screen.height/2 - size/8, size, size/4), TexturaNormal);
		GUI.DrawTexture (Rect(Screen.width/2 - size/8, Screen.height/2 - size/2 - intervalo, size/4, size), TexturaNormal);
		GUI.DrawTexture (Rect(Screen.width/2 - size/8, Screen.height/2 - size/2 + intervalo, size/4, size), TexturaNormal);
	}
}
