using UnityEngine;
using System.Collections;

public class CharMover : MonoBehaviour {
    public float maxSpeed = 6f;
    public int jumpHeight = 5;
    private Rigidbody body;
    private bool isGrounded = true;

    void Start() {
        body = GetComponent<Rigidbody>();
    }

    void Update() {
        float hSpeed = Input.GetAxis("Horizontal");
        float vSpeed = Input.GetAxis("Vertical");
        if (hSpeed != 0) {
            body.velocity = new Vector3(hSpeed * maxSpeed, body.velocity.y, 0f);

            // ensure character cannot get stuck (collider issues even with 0 friction)
            if (isGrounded) {
                transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y + 0.001f, transform.localPosition.z);
            }
        }
        if ((Input.GetKey(KeyCode.Space) || vSpeed > 0) && isGrounded) {
            GetComponent<AudioSource>().Play();
            body.AddForce(new Vector3(0, jumpHeight, 0), ForceMode.VelocityChange);
            isGrounded = false;
        }
    }

    public void OnCollisionEnter(Collision collision) {
        if (collision.gameObject.tag == "Ground") {
            isGrounded = true;
        }
    }
}

