Check if 2D object is at position
I have seen how to do this with a 3D sphere, but when I try to replicate it with a 2D box it has not worked (maybe it is the way I am trying to do it). I have a random position that I know and I just want to check if there is a 2D object in the position.
public bool Corridors() {
//create random location-sub/add 1 to prevent it from going to boarders
int randx = Random.Range(((width / 2) * -1) + 1, (width / 2) - 1);
int randy = Random.Range(((height / 2) * -1) + 1, (height / 2) - 1);
//position to insert/check
Vector2 rand_pos = new Vector2(randx,randy);
**//check if there is something at that position**
//clone wall to be at new random location
Instantiate(wall, rand_pos, Quaternion.identity);
//wall placement is good
return true;
}
Answer by streeetwalker · Mar 24, 2020 at 07:33 PM
Probably the easiest way is to do a Raycast to see if it collides with anything at that position. That means the objects that you want to detect need collider components, and make sure they're not Is Trigger. Look over this documentation - it's pretty simple: https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html
After doing some research on raycasts (mainly looking at the documentation) it worked with the following (in case anyone wants to know):
public bool Corridors() {
//create random location-sub/add 1 to prevent it from going to boarders
int randx = Random.Range(((width / 2) * -1) + 1, (width / 2) - 1);
int randy = Random.Range(((height / 2) * -1) + 1, (height / 2) - 1);
//position to insert/check
Vector2 rand_pos = new Vector2(randx,randy);
//check if there is something at that position
RaycastHit2D hit = Physics2D.Raycast(rand_pos, Vector2.up, 0f);
if (hit.collider != null)
{
//if raycast hits something at rand_pos, not empty
return false;
}
//clone wall to be at new random location
Instantiate(wall, rand_pos, Quaternion.identity);
//wall placement is good
return true;
}
Your answer
Follow this Question
Related Questions
Real concept of Vector2.Reflect 0 Answers
Rigidbody2D doesn't fall correctly when using MovePosition to move it horizontally 0 Answers
HELP! RigidBody2D position is acting incredibly goofy!! 0 Answers
How to set the Animator Controller in script. 0 Answers
Unity 2D: how to fire a renderline with raycast upward? 0 Answers