Home > Enterprise >  How to detect if an obstacle is a (specific amount) close to another same object and if so replace t
How to detect if an obstacle is a (specific amount) close to another same object and if so replace t

Time:07-26

So i have a game where there are 10 obstacles placed in a random about 15 x 300 area and i want them to always be 2 meters apart.

here is my code that generates the random obstacles:

{

public GameObject obstacle;
public int xPos;
public int zPos;
public int obstacleCount;




void Start()
{

    while (obstacleCount < 10)
    {
        xPos = Random.Range(-6, 7); 
        zPos = Random.Range(85, 245);
        Instantiate(obstacle, new Vector3(xPos, 1, zPos), Quaternion.identity);
        obstacleCount  = 1;

        
    }
}

}

How can i check that the obstacles are atleast 2 meters apart from eachother?

CodePudding user response:

In order to check distance between two objects, you'll have to be able to access and compare their positions. One way to do this is to store them all in an array as you instantiate them, like so:

GameObject[] obstacles = new GameObject[10];
while (obstacleCount < 10)
{
    xPos = Random.Range(-6, 7); 
    zPos = Random.Range(85, 245);
    obstacles[obstacleCount] = Instantiate(obstacle, new Vector3(xPos, 1, zPos), Quaternion.identity);
    obstacleCount  = 1;

    
}

In order to check if any are too close, you'll have to find the distance between them (you can do this by simply subtracting their position vectors):

Vector3 distance = obstacles[1].transform.position - obstacles[0].transform.position;  //order doesn't matter

Then simply check if the magnitude of the distance vector is less than your desired minimum length:

float minDistance = 2f;
if(distance.magnitude<minDistance)
{
    //two objects are too close
}

Just make sure you check each pair of obstacles; you can do probably do this with a couple for loops.

  • Related