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

public class VihuScript : MonoBehaviour
{
    public bool activ;

    bool onground;
    float lastcolltime;

    int flipo;
    public void Awake()
    {
        flipo = 1;
    }
    public void FixedUpdate()
    {

        onground = (Time.time - lastcolltime < 0.1f);

        if (activ)
        {
            GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
            Vector3 closest = players[0].transform.position;
            foreach (GameObject pl in players)
            {
                float d = (pl.transform.position - transform.position).sqrMagnitude;
                if (d < (pl.transform.position - transform.position).sqrMagnitude) closest = pl.transform.position;
            }
            GetComponent<Rigidbody2D>().AddForce((closest - transform.position).normalized * 5);
            if (Random.Range(0, 10) == 0 && onground)
            {
                GetComponent<Rigidbody2D>().AddForce(Vector3.up * Random.Range(30, 100) + Vector3.right * Random.Range(-100f, 100f));
            }
            else if (Random.Range(0, 50) == 0 && onground)
            {
                GetComponent<Rigidbody2D>().AddForce(Vector3.up * Random.Range(150, 400) + Vector3.right * Random.Range(-100f, 100f));
            }
        }
    }

    public void Update()
    {
        
        if (GetComponent<Rigidbody2D>().velocity.x > 0.1f) flipo = -1;
        if (GetComponent<Rigidbody2D>().velocity.x < -0.1f) flipo = 1;

        transform.localScale = new Vector3(transform.localScale.x*flipo, transform.localScale.y, transform.localScale.z);
    }

    private void OnCollisionStay2D(Collision2D collision)
    {
        lastcolltime = Time.time;
    }
}
