1
votes

I am trying to develop a 2d game where my enemies will pop-up and disappear in random position without overlapping with each other. I am following this tutorial in youtube https://www.youtube.com/watch?v=iLTP4EbM1N4 but when my player touch a enemy then he is losing 2 lives instead of 1. I think it's because enemies randomly spawn in the same spawnpoint (I have 5 enemies). Do you have any suggestion how to fix that? Any help would be highly appreciated. Thanks in advance. Here is my two scripts:

SpawnItems.cs

using UnityEngine;
using System.Collections;

public class SpawnItems : MonoBehaviour 
{   
    public Transform[] SpawnPoints;
    public float spawnTime = .5f;
    public GameObject[] Coins;

    void Start () 
    {
        InvokeRepeating ("SpawnCoins", spawnTime, spawnTime);
    }

    void Update () 
    {

    }

    void SpawnCoins()
    {
        for (int i = 0; i < Coins.Length; i++) {
            int spawnIndex = Random.Range (0, SpawnPoints.Length);

            //int objectIndex = Random.Range (0, Coins.Length);

            Instantiate (Coins [i], SpawnPoints [spawnIndex].position, SpawnPoints [spawnIndex].rotation);  

    }
}

Destroy.cs

using UnityEngine;
using System.Collections;

public class DestoryScript: MonoBehaviour 
{

    public float destoryTime = .5f;
    private float rotateSpeed = 300.0f;

    void Start () 
    {
        Destroy (gameObject, destoryTime);
    }

    void Update () 
    {
        transform.Rotate (Vector3.forward * Time.deltaTime * rotateSpeed);
    }
}

Orange ball overlaps with green ball

1
Can you confirm that an enemy is spawning at that point? Your Destroy method is taking .5 seconds to remove the object so maybe two collisions are occurring within that time frame?keyboardP
hi @keyboardP yes my enemy is spawning at that point & each enemy is taking .5 second to remove . But at the same time two enemies are overlapping at the same point. FYI: I have another script for my player.Afrin
pick a random position "possibleNewSpawnPoint". then carefully CHECK if that point is near any existing enemies. if it is TOO NEAR an existing enemy, pick ANOTHER random "possibleNewSpawnPoint". keep doing that until you get one that is not too close. this is an absolute basic pattern in game engineering.Fattie

1 Answers

-1
votes

Your SpawnCoins() in SpawnItems.cs should be like:

void SpawnCoins()
{
   Transform currentSpawnPoint = SpawnPoints[Random.Range(0, SpawnPoints.Length)].transform;

   Instantiate (Coins [Random.Range(0, Coins.Length)], currentSpawnPoint.position, currentSpawnPoint.rotation);  
}