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

public class SpawnCannonBall : MonoBehaviour
{
    public GameObject cannonBallPrefab;

    public int maxBalls = 100;

    public int ballCount = 0;
    private float spawnRate = 1.0f;

    private float minForce = 15.5f;
    private float maxForce = 22.5f;

    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(SpawnCannonBalls());
    }

    // Update is called once per frame
    void Update()
    {

    }

    IEnumerator SpawnCannonBalls()
    {
        while (ballCount < maxBalls)
        {
            yield return new WaitForSeconds(spawnRate);
            if(ballCount < maxBalls)
            {
                GameObject newBall = Instantiate(cannonBallPrefab, transform.position, cannonBallPrefab.transform.rotation);
                Rigidbody newBallRb = newBall.GetComponent<Rigidbody>();
                float speed = Random.Range(minForce, maxForce);
                newBallRb.AddForce(transform.up * speed, ForceMode.Impulse);
                newBall.GetComponent<Id>().id = ballCount;
                ++ballCount;
            } else
            {
                StopCoroutine(SpawnCannonBalls());
            }
        }
    }
}
