Pixel perfect collision based on alpha channel of a PNG image

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By dejvid_bejlej

In short: check if two sprites are overlapping, check if pixels of two sprites with alpha > 0 are overlapping, mark collision.

The idea I’m talking about is explained here:
https://www.youtube.com/watch?v=Dspz3kaTKUg&feature=youtu.be&t=200&ab_channel=KidsCanCode
from 3:20 to around 5:00.

I know you can animate collision shapes in godot, but that would require ridiculous amount of work to achieve this level of detail. I wan’t to make 2d combat system and adequate collision detection is super important.

Is it possible to make this in GDscript or maybe C++/C# in Godot?

I’d start with simple collision shapes which then trigger a bitwise collision check.
The “BitMap” class may be of help here. It allows converting image alpha into an array of booleans:
BitMap — Godot Engine (3.1) documentation in English

If the Sprites are 64 or less Pixels wise you could i.e. convert such a “BitMap” into an array of Integers (one per Line) which represent the alpha in binary form.
For collision check the binary shift the int and the array index depending on the relative pixel coords of the two colliders. Then binary AND boths ints and there’s a collision when the result is >0.

An example for one line:
Sprite A: 010100
Sprite B: 011101
Sprite B is 2 pixels right of Sprite A so shift binary value 2 bits to the right: →
maskB[lineix] >> 2 => 00111101
Then bit AND: 010100 & 00111101 ==> 00010000 >0, so it is a collision.

See here for bitwise operators:
GDScript basics — Godot Engine (3.1) documentation in English

But this is just one idea. Maybe there are easier ways.

wombatstampede | 2019-03-27 09:57

:bust_in_silhouette: Reply From: jjdibble21

Try to click on the sprite that your using, then press sprite and then Create CollisionPolygon2D Sibling. Then set the simplification down to 0 and the shrink and grow down to 0. Not great on performance but just up the simplification for it.