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

public class FoodSpawner : MonoBehaviour
{

    [SerializeField] GameObject[] foodPrefabs;

    Vector3 previousPosition;
    float distanceTravelled;
    float spawnDistanceRate = 5f;
    float spawnRange = 10;

    void Update()
    {
        var currentPosition = transform.position;
        distanceTravelled += (currentPosition - previousPosition).magnitude;
        previousPosition = currentPosition;

        if (distanceTravelled > spawnDistanceRate)
        {
            SpawnFood();
            distanceTravelled = 0;
        }
    }

    void SpawnFood()
    {
        var spawnDirection = Random.insideUnitCircle.normalized;
        var relativeSpawnPosition = spawnDirection * spawnRange;
        var spawnPosition = (Vector2)transform.position + relativeSpawnPosition;
        var choice = Random.Range(0f, 1f) < 0.8f? 0 : 1;

        var food = Instantiate(foodPrefabs[choice], spawnPosition, Quaternion.AngleAxis(Random.Range(0, 360), Vector3.forward));
        var foodRigidbody = food.GetComponent<Rigidbody2D>();
        if (foodRigidbody)
        {
            foodRigidbody.AddForce(-spawnDirection * Random.Range(1,10));
        }
    }
}
