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

public class SpawnWithForce : MonoBehaviour
{
    public GameObject prefab;
    public Vector3 force;
    public bool randomForce = false;
    public float randomForceAmount = 5f;

    [Range(0.1f, 8f)]
    public float spawnRate = 1f;
    public bool randomRotation = false;

    public bool randomSize = false;
    public Vector2 sizeRange = new Vector2(0.1f,3f);

    void Start()
    {
        StartCoroutine(Spawn());
    }

    IEnumerator Spawn()
    {
        while (true)
        {
            Quaternion rot = (randomRotation) ? Random.rotation : transform.rotation;

            var obj = Instantiate(prefab, transform.position, rot);

            var newForce = force;
            if (randomForce)
            {
                newForce = newForce + Random.insideUnitSphere * randomForceAmount;
            }

            Rigidbody rb = obj.GetComponent<Rigidbody>();
            rb.AddForce(newForce, ForceMode.Impulse);

            if (randomSize)
            {
                float newScale = Random.Range(sizeRange.x, sizeRange.y);
                obj.transform.localScale = obj.transform.localScale * newScale;
                rb.mass = rb.mass * newScale; // scale affects mass
            }
                

            yield return new WaitForSeconds(1f / spawnRate);
        }

    }
}
