问题
Iam trying to make a simple 2d platformer game in unity. I managed to move the player and all other stuffs. The problem now i am facing is that the prefabs that randomly spawned onto the game is overlapping. So my question is how to prevent the overlapping of game objects. The prefabs i used is having different dimension(length). Here is the c# code i used:
public class spawnscript : MonoBehaviour {
public GameObject[] obj;
public float spawnMin;
public float spawnMax;
// Use this for initialization
void Start () {
Spawn ();
}
void Spawn()
{
Instantiate (obj [Random.Range (0, obj.GetLength (0))], transform.position, Quaternion.identity);
Invoke ("Spawn", Random.Range (spawnMin, spawnMax));
}
}
回答1:
void Spawn() {
Instantiate(obj [Random.Range (0, obj.GetLength (0))], transform.position +(ADD OFFSET HERE WITH PREVIOUS OBJECTS Position), Quaternion.identity);
Invoke("Spawn", Random.Range (spawnMin, spawnMax));
}
回答2:
List<Vector3> existingPositions = new List<Vector3>();
void Spawn()
{
var pos = RandomizePosition();
if(HasOverlapped(existingPositions, pos)) // Your own logic to implement
{
//Either randomize the position again, or give it an offset, up to you
}
else
{
Instanciate(pos, ...);
existingPositions.Add(...);
}
}
来源:https://stackoverflow.com/questions/28891679/prevent-overlapping-of-spawned-game-objects-in-unity