- Home /
In a closed room Instantiate game objects around the player randomly.
Hi, I want to instantiate objects around the player. Here player will be in a closed room. if the player is near the wall i want to instantiate objects on the other side of player and none of the objects should not collide each other. instantiated objects will 1-20. In any case objects should not instantiate outside the room. . any help would be grateful. thanks in advance.
Answer by tormentoarmagedoom · Jan 10, 2019 at 12:40 PM
Good day.
Then you first need to generate random positions to spawn objects.
To create positions, you should use something like this (i do an example in 2D for easy understand, you should do it with Vector3):
Lets imagine your area limits are from x=-10 to x=10 and from y=-20 to y=20
Vector2 possiblePosition = new Vector2 (Random.Range(-10,10), Random.Range(-20,20);
This will generate a random position inside your area. Now you need to know if is not too much close to any other object. So, you need something to detect other objects. Best way I think is to make all instantiated objects have the same TAG, so you can easy find them, for example "InstObj". And the player lets say have the TAG "Player"
So, when you instantiate the firstone, only need to check for the player position. I normally use the Distance function. If i detect the distance between the player and the new object is less than 2, i will need to create a new random position, until i get a random position away from other objects.
Vector3 FindGoodPosition()
{
Vector2 possiblePosition = new Vector2 (Random.Range(-10,10), Random.Range(-20,20);
while (Vector3.Distance( GameObject.FindObjectWithTag("Player").transform.position, possiblePosition) <2)
{
possiblePosition = new Vector2 (Random.Range(-10,10), Random.Range(-20,20);
}
}
This way you will have a position always inside the area and at leas 2 units away from the player. Now lets check with all other objects
foreach (GameObject ObjectToCheck in GameObject.FindObjectsWithTag("InstObj"))
{
if (Distance between possiblePosition and ObjectToCheck .transform.position <2)
{
return = null;
}
}
return possiblePosition;
}
This way this methos will only return a position if its correct, if not, it will return null, so to instantiate the objectit, you must do something like this:
Vector3 Positiontospawn = FindGoodPosition();
while (Positiontospawn == null)
{
Positiontospawn = FindGoodPosition();
}
Instantiate (ObjectPrefab, Positiontospawn, rotation);
Good Luck!
PD: This is a guide, not a script to copy paste, try to understand ALL it does, or you will never succeed in game develop.
Bye!