• Resources
  • Small code snippet for optimising Tilemap collisions

Hi, While learning Godot I came across an issue with physics collision and, specifically, tilemaps. The problem is not Godot specific, it tends to occur in pretty much any "soft" physics simulations.

The issue manifests as a dynamic physics object, under gravity, sticking intermittently when it crosses a boundary between adjacent tiles (or other static objects whose upper surfaces are on the same plane).

Some fixes (such as adding a second, round, collision shape to the dynamic object) work to some extent but are far from perfect.

Here is my solution, at least for tilemaps, which is to join collision rectangles for adjacent tiles, therefore doing away with the troublesome boundaries and, as a side benefit, optimising the collision process (as it reduces the number of collision rectangles).

The link above is an example scene with a tilemap that is optimised to reduce the collision rectangles.

The work is done by the functions in "Tilemap_MergeCells.gd". The "merge" function returns an array of Rect2`s which describe each of the rectangles found in cell coordinates. The calling script scales these by the size of the tiles and creates collision rectangles for them that it adds as children to the attached StaticBody2D.

It assumes a square tilemap with square, completely filled, tiles. If you have any tiles which are not like this you should still be able to create a normal collision shape for them and then send their cell id(s) to the "merge" function in a "to be excluded" array.

I have included a simple debug drawing fuction to show where the collision rectangles have been created.

I hope this helps anyone else with similar issues.

Cheers, Ratty

Cool resource, thanks for sharing!

BTW, you seem to have created a duplicate topic rather than editing it to add a tag. I've deleted the other, but in the future you can just contact the forum staff if you need help. :)

Thanks, not sure how I managed that, probably pressed "back" in my browser :s

4 years later

Did something similar

Here is a link to the Gist:

  • 0x78 replied to this.
    a year later