Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add colliders to complex maze

Tags:

c#

unity3d

I downloaded a maze sprite for expiremental purpose to use in my game and I'm trying to add colliders to the wall. But since the maze is complex, it is quite a lot of work to add a Box collider 2D to each wall.

I tried using the Polygon collider 2D and it was some sort of inaccurate mesh looking collider.Is there any better way to add colliders to a maze or is it possible to do it programmatically adding colliders by somehow detecting the structure of the maze?

Here is something similar to the maze I'm using:

Add comment

like image 479
Karan Avatar asked May 24 '19 17:05

Karan


1 Answers

There are a few answers to this question, depending on your approach.

1. Sprite-based Approach (where you have an image of a maze)
Make sure that the sprite is transparent, and only opaque on the wall areas (a PNG image can have transparency). After you do this, then you should be able to attach a polygon collider to automatically create a collider. If the image is too big/complex like you say, then you might want to split it up into several different images (4 quadrants for example), and then arrange them and attach a polygon collider to each object. In general, the simpler a collider is, the more accurate and efficient it is.

The downside to the above approach is that you are having to do a lot of manual work. If you knew that you had a lot of hand-drawn mazes that you would need to build colliders for like this, then it might be worth automating the process described above with a script, but that could get complicated fast unless you know what you're doing. Essentially, the automation script could recursively split the sprite into quadrants, create corresponding GameObjects, and add PolygonColliders to each one.

Manually splitting the image in a photo-editing program or making an algorithm to generate the maze and colliders might be faster for you than automation, depending on how much you want to get into the code.

2. Algorithm-based Approach
Luckily, there are a lot of maze programming tutorials online. Most are for 3D mazes, but the logic is the same to make a 2D maze. If you're interested in this option, then I found tutorials on the topic here, and here. In order to add collision after the maze is generated in each of these tutorials you can add a BoxCollider2D to each side of each cell which has a wall (or if using a prefab, add a BoxCollider2D to the prefab).

like image 186
Nicholas Bucher Avatar answered Sep 23 '22 00:09

Nicholas Bucher