0
\$\begingroup\$

I want to check if the position I generated has another object or not. I do this by using Raycast:

private void RandomOBS()
{
    Vector3 pos = new Vector3(UnityEngine.Random.Range(-8f, 8f), UnityEngine.Random.Range(-4f, 4f), 0);

    while (Physics2D.Raycast(pos, pos).collider)
      pos = new Vector3(UnityEngine.Random.Range(-8f, 8f), UnityEngine.Random.Range(-4f, 4f), 0);
}

The code above doesn't work at all. I tested it with if statement and for some reason it cannot check that position.

private void RandomOBS()
{
    Vector3 pos = new Vector3(UnityEngine.Random.Range(-8f, 8f), UnityEngine.Random.Range(-4f, 4f), 0);

    while (Physics2D.Raycast(transform.position, transform.position).collider)
      pos = new Vector3(UnityEngine.Random.Range(-8f, 8f), UnityEngine.Random.Range(-4f, 4f), 0);
}

However when you check the transform.position instead of the pos, it works? How and why? All the game objects have the correct colliders & stuff.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Rays detect where they cross the edge of a shape from outside to inside. If your start position is already inside the shape, you might not get a hit at all. You should use overlap queries instead or rays for this purpose. \$\endgroup\$
    – DMGregory
    Feb 17, 2020 at 10:56

2 Answers 2

2
\$\begingroup\$

I would assume you actually want to use the Physics2D.OverlapArea function instead.

It takes in two Vector2's which are the top left corner and bottom right corner of a rectangle. The result is a Collider2D that the function found was overlapping the input rectangle.

So your function would be:

private void RandomOBS()
{
    Vector2 pos = new Vector2(UnityEngine.Random.Range(-8f, 8f), UnityEngine.Random.Range(-4f, 4f);

    while (Physics2D.OverlapArea(pos - rectangleExtent, pos + rectangleExtent) != null)
        pos = new Vector2(UnityEngine.Random.Range(-8f, 8f), UnityEngine.Random.Range(-4f, 4f);
}

The variable rectangleExtent is also a Vector2 which is how far away the position has to be from another already existing collider

I should also say that this only works in 2D, Though you could use Physics.OverlapBox instead for 3D.

That function takes in a center and half extent as Vector3's

So in the case of 3D it would be something like this:

private void RandomOBS()
{
    Vector3 pos = new Vector3(UnityEngine.Random.Range(-8f, 8f), UnityEngine.Random.Range(-4f, 4f), 0);

    while (Physics.OverlapBox(pos, boxExtent).Length > 0)
        pos = new Vector3(UnityEngine.Random.Range(-8f, 8f), UnityEngine.Random.Range(-4f, 4f), 0);
}

And the variable boxExtent is basically the same as rectangleExtent just in 3D

\$\endgroup\$
0
\$\begingroup\$

I can solve the problem by using Physics2D.Linecast(pos, pos).collider instead of Physics2D.Raycast(pos, pos).collider if anyone has any idea please let me know.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .