using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Rigidbody))]
public class SpeederControls : MonoBehaviour 
{
    public float forwardPower = 10.0f;
    public float minForwardPower = 3.0f;
    public float strafePower = 50.0f;
    //public float turnTorque = 10.0f;

    public float controlDeadZone = 0.05f;

    public Camera controllingCamera = null;
    public Transform cameraTarget = null;

    public float dragPointDistance = 10.0f;
    public float springK = 80.0f;
    public float springC = 20.0f;

    public float pointDecceleration = 0.85f;

    public Transform raycastPoint;
    public float raycastDistance = 50.0f;    

    private Vector3 m_dragPoint = new Vector3();

    void FixedUpdate()
    {
        if (!Player.instance.isActive)
            return;

        if (Physics.Raycast(raycastPoint.position, -Vector3.up, raycastDistance))
        {
            float power = forwardPower;
            float vertPower = Input.GetAxis("Vertical");
            if(vertPower < controlDeadZone)
                power = minForwardPower;

            Vector3 diff = cameraTarget.position - controllingCamera.transform.position;
            diff.Normalize();
            diff.y = 0.0f;
            Vector3 forwardForce = diff * (power);
            rigidbody.AddForce(forwardForce, ForceMode.VelocityChange);
            
        }

        rigidbody.AddForce(controllingCamera.transform.right * (strafePower * Input.GetAxis("Mouse X")), ForceMode.VelocityChange);
    }

    void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.black;
        Gizmos.DrawSphere(m_dragPoint + transform.position, 3.0f);
        Gizmos.DrawLine(transform.position, m_dragPoint + transform.position);

        Gizmos.color = Color.red;
        Gizmos.DrawLine(raycastPoint.position, raycastPoint.position - Vector3.up * raycastDistance);
    }
}
