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

public class PolceCarScript : MonoBehaviour
{
    public Transform playerTransform;
    public Movement playerMovement;


    public Vector3 velocity;
    public float acceleration;

    public float crashDistance;
    public float crashStrength;
    bool crash;
    public float crashCooldown;
    public float timeSinceLastCrash;

    public float radiansDelta;

    public AudioSource audioSource;

    private void OnCollisionEnter(Collision collision) // if a collision occurs with collision boundaries
    {
        velocity = Vector3.zero;
    }

    private void OnEnable()
    {
        audioSource.Play();
    }

    private void OnDisable()
    {
        audioSource.Stop();
    }

    void Update()
    {
        Vector3 moveDir = playerTransform.position - transform.position;
        float dist = moveDir.magnitude;
        moveDir.y = 0;
        moveDir = moveDir.normalized;


        velocity = Vector3.RotateTowards(velocity, moveDir, radiansDelta, 0.0f);
        velocity -= 0.2f * velocity * Time.deltaTime; // friction
        

        transform.rotation = Quaternion.LookRotation(velocity, Vector3.up);
        velocity += moveDir * acceleration * Time.deltaTime;

        if (dist < crashDistance && timeSinceLastCrash >= crashCooldown)
        {
            timeSinceLastCrash = 0.0f;

            //playerMovement.onGround = false;
            
            playerMovement.launchInDir((moveDir + Vector3.up).normalized * crashStrength); // instantenous velocity
            //playerMovement.characterController.Move(velocity * Time.deltaTime);
        }

        timeSinceLastCrash += Time.deltaTime;

        transform.position += velocity * Time.deltaTime;
    }

}
