How to create a mask from a sprite in order to do sprite overlap detection?

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

I have been trying to figure out a way to do sprite overlap detection in Godot 3.

Answers to a previous question of mine recommended that I content myself with bounding rectangles or polygons. Stubbornly, I am still pursuing the dream of sprite overlap detection.

I was spoiled by Pygame, which has a simple method to create masks from sprites, and then check them for overlap using a collide_mask() method.

Godot doesn’t have anything like this built in, but it should still be possible to do it in the engine.

I discovered that Textures have a get_data() method which returns an Image. Further, Images have a get_pixel()method which returns the color data of each pixel in the image. Here is a link to the documentation on Images.

I was thinking that it should be possible to use this data to construct a mask, whose coordinates can then be translated to world space. Once we have this, we can easily test if two masks overlap. And voila, sprite overlap detection!

The problem is that I don’t know how to implement this.

Any advice?

:bust_in_silhouette: Reply From: alfandango

I’m very new to godot 3

I’ve just been reading through the docs and I think what you are asking is described in the physics documentation. Collision Layers and Masks


  • This describes the layers that the object appears in. By default, all bodies are on layer 1.


  • This describes what layers the body will scan for collisions. If an object isn’t in one of the mask layers, the body will ignore it. By default, all bodies scan layer 1.

Thanks for the response. Those docs deal primarily with CollisionObject2D and the nodes that inherit from it. Unfortunately, Sprites and Textures do not inherit from this node and so don’t have the same type of in-built collision detection resources. The type of “mask” I’m talking about in my question isn’t the same as what Godot calls a “mask” in that article.

Diet Estus | 2018-06-04 00:05

Oh, sorry couldn’t be of help then.

alfandango | 2018-06-04 00:07

Can you not wrap the texture or sprite in a KinematicBody2D node then use the move_and_collide ( Vector2 rel_vec ) method. see KinematicBody2D

KinematicCollision2D move_and_collide ( Vector2 rel_vec )
Moves the body along the vector rel_vec. The body will stop if it collides. Returns a KinematicCollision2D, which contains information about the collision.

alfandango | 2018-06-04 00:15

That method would use the KinematicBody2D’s collision shape to determine collision, not the child Sprite. There is currently no in-built way to detect Sprite collision in Godot, so I’m fairly sure you have to use the image data in a way similar to what I suggest.

Diet Estus | 2018-06-04 14:20