Small code snippet for optimising Tilemap collisions

RattyRatty Posts: 4Member
edited July 2 in Resources

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


Tags :

Comments

  • MegalomaniakMegalomaniak Posts: 1,585Admin

    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. :)

  • RattyRatty Posts: 4Member

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

Sign In or Register to comment.