Unity:在C#中随机位置重叠生成随机对象

时间:2016-07-16 14:56:40

标签: c# unity3d

我正在尝试开发一个2D游戏,我的敌人会弹出并随机摆放而不会相互重叠。我在youtube https://www.youtube.com/watch?v=iLTP4EbM1N4中关注这个教程,但是当我的玩家碰到一个敌人时,他正在失去2个生命而不是1个。我认为这是因为敌人在同一个生成点中随机产生(我有5个敌人)。你有什么建议如何解决这个问题?任何帮助将受到高度赞赏。提前致谢。这是我的两个脚本:

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 个答案:

答案 0 :(得分:0)

SpawnCoins()中的SpawnItems.cs应该像:

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

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