Search 3x3 grid around player

I’m trying to build a simple 2D game and I need to know everything within 1 unit of the player. This means left, right, up, down, and all 4 corners.

000

010

000

This is a text representation of what I need. The 0’s are all the squares I need to check, and the 1 is the player (I will be checking their square as well.) The player and all gameobjects will be lined up 1 to 1 with the built in unity grid, so I’ll be working with whole numbers. I’ll be using prefabs, so I won’t know the gameobjects exact names if that matters. Do I need to make my own grid to check using nodes in order to do this? How do I check those 9 areas and how can I store the co-ordinates of the area if there is a gameobject there?

I’d rather not use raycasts, but if I have to then I suppose I will.

I suggest using a 2-dimensional array [,] to keep track of the objects in your grid. This way, you can easily find neighbors. The way that needs less maintenance but is far more resource-intensive is to loop through all gameobjects in the scene and compare their Mathf-FloorToInt-rounded transform.positions to the grid position you are searching for.

–

1 Answer

1

First of all, raycasts are cheap and amazing. Very efficient. If you’re not wanting to make your own grid system, which would be best for all future work, then I would try something like a boxcast. Like a raycast, but box shaped and just tell it to check those certain areas around the player one by one using a For Loop.

But really your own grid system would save you a lot of time in the long run. But if your game is short or just for your own experience then I could see just skipping it for now and focusing on other aspects. Custom Editors are amazing though and you should look into them.