- Home /
The question is answered, right answer was accepted
From one gameobject, detect surrounding objects
My objective here is to have each generated 2d object [Block] detect whether there is an object above, below, or to the right or left.
What would be the best way to do this?
Are the objects on a grid or are they free to be anywhere?
The current generation is grid-like, but they are free to be anywhere. Its generating a cave system
Answer by LeFlop2001 · Feb 02, 2020 at 04:15 PM
you could do that by giving every block a collider and then using the Physics2D.CircleCast() function, which returns a list of collides within the circle you cast. But I’m guessing you’re positioning your blocks in a strict grid. In that case the best solution would be to store all the blocks in a two dimensional array based on their x and y position. This way you can easily check surrounding blocks by entering the blocks position plus/minus 1.
Gameobject[,] blocks;
public GameObject blockPrefab;
public Vector2Int start;
public Vector2Int end;
void Start()
{
blocks = new GameObject[Mathf.Abs(start.x)+Mathf.Abs(end.x),Mathf.Abs(start.y)+Mathf.Abs(end.y)];
for(int x= start.x ; x < end.x ; x++)
{
for(int y= start.y ; y < end.y ; y++)
{
GameObject go = Instantiate(blockPrefab,new Vector2 (x,y),Quaternion.Euler(0,0,0));
blocks[x-start.x,y-start.y] = go;
}
}
}
Follow this Question
Related Questions
Brick Breaker - Ball not bouncing back from the brick. 2 Answers
Rigidbody and Collision choices for 2D Adventure 0 Answers
How to check if an object hits the ground hard enough then add explosive force around it (2D) 1 Answer
How do you make a car drift in unity 2D 1 Answer
Snake Movement Problem 0 Answers