- Home /
Spawning animals at a random postion on platforms.
Im making an action 2D platfomer, and to make the world more alive, I wanted to add someanimals that will jump around and stuff. BUT I dont know how to make them spawn on the level, and not just spawn in it, or fall out of the level.
^ the kind of level these animals are gonna spawn on.
You know the width and height of the map? get a random point within that range, raycast down to find the closest ground level point and spawn an enemy on that point.
Answer by Rapizer · Apr 13, 2021 at 08:12 AM
You can make empty game objects located at where you want your animals to spawn with the tag SpawnPoint and make the animals instantiate at a random spawn point. (untested code)
public GameObject animal; // animal you want spawned
// Start is called before the first frame update
void Start()
{
// an array of spawn points
GameObject[] spawnPoints = GameObject.FindGameObjectsWithTag("SpawnPoints");
// does this code 3 to 5 times (you can replace the value with whatever you want)
for (int i = 0; i < Random.Range(3, 5); i++)
{
int spawnPointindex = Random.Range(0, spawnPoints.Length); // random number between 0 and the number of spawn points
// pick a random spawn point from the array and get the position of it
Vector3 randomPos = spawnPoints[spawnPointindex].GetComponent<Transform>().position;
// instantiate animal at random position
Instantiate(animal, randomPos, Quaternion.identity); // instantiate the animal at the random position
}
}
If you want random animals, you can turn the variable animal into an array and get a random index of the array and spawn that animal.
public GameObject[] animals; // array of animals
getting a random animal from the array: (put this code inside the for loop and replace animal with randomAnimal)
int animalIndex = Random.Range(0, animals.Length);
GameObject randomAnimal = animals[animalIndex];
Answer by thereadypunk · Apr 23, 2021 at 07:18 AM
@Rapizer thanks for the answer, but It is not truly random. Since its preset spawn points.I would rather not spam spawn points all over the place. I can, but that might be to many game objects.
Your answer
Follow this Question
Related Questions
Problem with rotated colliders 0 Answers
One-way platform's side causes collision with Platform Effector 1 Answer
2D Sidescroller enemy AI jump help! Picture Included! 3 Answers
I'm trying to make platforms generate between two platforms which are already generated. 0 Answers
Make a game object "carry" other 1 Answer