Automatically match collider bounds with sprite size in Unity


So I thought to post some (not unique, I believe) but at least interesting (a bit) solutions I took while developing this game. Maybe this could be helpful for other newbie developers doing 2d projects in Unity.

The game was developer for "I Can't Draw" game-jam and at some point, maybe on the 2nd day of development I ended up with a hand-crafted levels which was mainly consists of islands made out of sprites with colliders set by hand on each. I did a couple of playtests and realized that pre-crafted levels are boring and will require a lot of time to compose, so I've decided to make the levels be randomly generated.

At the time I had 3 pre-created inslads and being placed them randomly on the player path, which is quite boring obviously. So I decided to make the islands to be randomly generated instead of being pre-created by me. I quickly realized that this is not going to work with pre-built sprites and hence hand-defined colliders for them because I want the islands to have random height and random length (sic!).

I needed the colliders to follow the randomly set size of sprites. It look me quite a while until I finally come to a working solution:

public class Island : MonoBehaviour {
public float minSize = 1f;
public float maxSize = 2f;
public float minHeight = 1f;
public float maxHeight = 2f;
void Start()     {
 // Saves initial sizes
 _renderer = GetComponent<spriterenderer>();
 _collider2D = GetComponent<boxcollider2d>();
 initialSize = _renderer.size;
 Vector2 colliderInitialSize = _collider2D.size;
 // Randomize sprite width
 _renderer.size = new Vector2(
                initialSize.x * Random.Range(minSize, maxSize),
                _renderer.size.y
            );
 // Randomize collider width
 _collider2D.size = new Vector2(
                colliderInitialSize.x + (_renderer.size.x - initialSize.x),
                colliderInitialSize.y
            );
 // The below randomizes island height, this was optional
 initialSize = _renderer.size;
 var yDiff = initialSize.y - _collider2D.size.y;
 // Randomize sprite height
 _renderer.size = new Vector2(
                initialSize.x,
                _renderer.size.y * Random.Range(minHeight, maxHeight)
            );
 // Randomize collider height
 _collider2D.offset = new Vector2(
                _collider2D.offset.x,
                _renderer.size.y / 2 - yDiff/2
                );
            
 _collider2D.size = new Vector2(
                _collider2D.size.x,
                _renderer.size.y - yDiff
               );
}
}

Making this a script and attaching to an island prefab with some more additions I was able to just put the numbers into the fields and get a nicely randomized island with colliders match the sprite bounds.


Resulting in a nicely generated levels:

Get Wonderful Duck

Download NowName your own price

Leave a comment

Log in with itch.io to leave a comment.