How to check if a world position has a collider? (UNITY 2D)

Hey! I have a game with a tilemap where some of the tiles has colliders attached to them. When I spawn my enemies, I dont want them to spawn at a position where there is a collider so I wrote this simple script:

        private bool CellHasCollider(Vector3 cellWordPosition)
        {
            // Raycast at position
            // If not null -> true
            // Else -> false
            var c = Physics2D.OverlapBox((Vector2) cellWordPosition, new Vector2(1, 1),
                0);

            return c != null;
        }

However, this does not work with my tiles that has a collider and enemies do still spawn inside of it:
8500169--1131770--upload_2022-10-9_14-24-38.png

Underlying collider:
8500169--1131773--upload_2022-10-9_14-25-2.png

What am I missing? :slight_smile:

Well your code would work so you’ve got something else going wrong. If you want to know if a specific 2D world position is overlapping then use OverlapPoint.

To note though, you don’t add “colliders to tiles”. There’s only a single TilemapCollider2D and it creates physics shapes if the collider-type for that tile asks for one.

So you know, your call above is checking for a 1x1 box with zero rotation on ANY collider in the world, not a specific one such as your TilemapCollider2D. You’re also not filtering by layer-mask etc.

1 Like

btw, I can only presume that “cellWordPosition” means “cellWorldPosition”? It needs to be a postion in world-space, not tile-space i.e. a local tile position.

1 Like

Thank you, there were some mix-up of different tilemaps which made the collider not react! Thank you for confidence in that I at least was using the OverlapBox method right!

1 Like