🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Is there a more efficient way to check nearby tile locations for colliders?

Started by
2 comments, last by Alberth 3 years, 11 months ago

So am building a turn based game and something I need to be able to track is what nearby tiles are open so I currently have this code:

var selfPosition = gameObject.transform.position;
var availableNearbyPositions = new HashSet<Vector3>();
var hits = new RaycastHit2D[1];
var layerMask = LayerMask.GetMask(LayerName.CHARACTER) + LayerMask.GetMask(LayerName.GROUND);
  
var scanRadius = 3;

for (int x = -scanRadius; x <= scanRadius; x++) {
  for (int y = -scanRadius; y <= scanRadius; y++) {
    if (x == 0 & y == 0) {
      continue;
    }
      
    var checkPosition = VectorUtility.Round(new Vector3(selfPosition.x + x, selfPosition.y + y, 0), 1);
    Physics2D.RaycastNonAlloc(
      checkPosition, 
      Vector2.zero, 
      hits, 
      float.PositiveInfinity, 
      layerMask
    );

    if (hits[0].collider != null) {
      hits[0] = new RaycastHit2D();
      continue;
    }
      
    availableNearbyPositions.Add(checkPosition);
  }
}

So this code does give the desired effect however I am wondering if there is a more efficient way to do this. based on my profiling, this piece of code executed for 100 entity that are being tracked takes about 5ms.

While I might be able to figure out a way to scope down the amount of entities that I do this check for on each turn (and I am open to suggestions on this part too), I liked to know if there is a way I can trim down that 5ms down since that is close to half of the time I want to use for a frame, any suggestions?

Advertisement

I am assuming that by ‘open’ you mean that there is no object blocking the tile, so couldn't you maintain an array of booleans corresponding to your tile map which indicates which tiles are occupied and which are open?

Never done anything Unity or raycasting, but some thoughts:

  • Isn't “infinity” distance a bit far for 'nearby' tile checks? Ie something at the other end of the world is also 'near'?
  • You're trying rays through every grid position around the object in a 5x5 (or maybe even 7x7) square. Is there anything you'd miss if you only try rays by iterating through the edge squares? The ray starts at the center, so it would check all inner tiles as well wouldn't it?

This topic is closed to new replies.

Advertisement