- Home /
Enemies spawning close/ on top of the Player.
Hi there! I made a script which generates a random map layout and in which every tile is added in a list. After the map is done generating i spawn enemies on random tiles from the list, but the problem is that they even spawn on top of the player or very close to the player and you dont even have time to react. I have tried some stuff to avoid this from happening but my efforts were unsuccessful.
Here is the code for spawning the enemies:
void SpawnEnemies() { while(enemyCounter != 0) { int rand = Random.Range(0, enemies.Length); Instantiate(enemies[rand], createdTiles[Random.Range(0, createdTiles.Count)], Quaternion.identity); enemyCounter--; } }
Answer by betaFlux · Dec 31, 2018 at 11:18 AM
You would have to cache the player tile before you spawn your enemies:
public class Player : MonoBehaviour {
public Tile currTile;
private void Awake() {
currTile = Tilemap.GetTileAtWorldPosition(this.transform.position);
}
}
Where GetTileAtWorldPosition inside the Tilemap class could look like this:
void GetTileAtWorldPosition(Vector2 pos) {
return tiles[pos.x, pos.y]; // If tiles are placed on coordinates with whole numbers and have a scale of 1
}
Then you could filter out the player tile before instantiating enemies:
void SpawnEnemies() {
List<Tile> validTiles = new List<Tile>();
for(int i = 0; i < createdTiles.Count; i++) {
Tile t = createdTiles[i];
if(t == Player.currTile) {
continue;
}
validTiles.Add(t);
}
while(enemyCounter != 0) {
int rand = Random.Range(0, enemies.Length);
Instantiate(enemies[rand], validTiles[Random.Range(0, validTiles.Count)], Quaternion.identity); enemyCounter--;
}
}
Thanks! I managed to surpass my problems by using some of your concepts. You rock! :D