﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class MoveScript : MonoBehaviour
{

    public Transform camFootTransform;
    private Rigidbody camFootRb;

    Rigidbody rb;

    public float speed = 2000;
    public float jumpForce = 400;

    bool canJump = true;

    public bool needJumpTag = false;

    public bool highDrag = true;

    private void Start()
    {
        rb = GetComponent<Rigidbody>();
        camFootRb = camFootTransform.GetComponent<Rigidbody>();
    }

    void OnCollisionEnter(Collision collision)
    {
        if (needJumpTag == true)
        {
            if (collision.gameObject.tag == "Floor")
            {
                canJump = true;
            }
        }
        else
        {
            canJump = true;
        }
    }

    void FixedUpdate()
    {
        if (transform.position.y < -10)
        {
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
            //GameControllerScript.shared.Die();
            //print("du er død");
        }

        if (highDrag)
        {
            float velY = rb.velocity.y;
            rb.velocity = new Vector3(rb.velocity.x * 0.9f, velY, rb.velocity.z * 0.9f);
        }

        if (Input.GetKey(KeyCode.W))
        {
            Vector3 newDir = camFootTransform.forward;
            newDir.y = 0f;
            rb.AddForce(newDir * Time.fixedDeltaTime * speed);
        }
        if (Input.GetKey(KeyCode.S))
        {
            Vector3 newDir = -camFootTransform.forward;
            newDir.y = 0f;
            rb.AddForce(newDir * Time.fixedDeltaTime * speed);
        }
        if (Input.GetKey(KeyCode.A))
        {
            rb.AddForce(-camFootTransform.right * Time.fixedDeltaTime * speed);
        }
        if (Input.GetKey(KeyCode.D))
        {
            rb.AddForce(camFootTransform.right * Time.fixedDeltaTime * speed);
        }
    }

    private void Update()
    {
        if (canJump == true)
        {
            if (Input.GetKeyDown(KeyCode.Space))
            {
                canJump = false;
                rb.AddForce(camFootTransform.up * jumpForce);

                if (camFootRb != null)
                {
                    camFootRb.AddForce(camFootTransform.up * 400);
                }
            }
        }
    }
}
