user13875552
user13875552

Reputation:

How to detect that a sprite has encountered a color in pygame

I want to detect that the sprite has encountered a color in pygame, which function should I use to achieve this function.

Upvotes: 0

Views: 536

Answers (1)

Glenn Mackintosh
Glenn Mackintosh

Reputation: 2780

Though it is possible to get the color at any point in the surface that you want to check against using get_at() (docs here). You would need to find the new area that your sprite covered that it did not cover last time and check every pixel in that, and if other things were moving around you would have to check if your sprite now overlapped with any of those area and check that. Or you could decide that was too complicated and just run through every pixel under your sprites location (without you sprite drawn yet) and check for that color.

It is possible, but would likely not be very fast.

An alternative is if you know where those colors are you can mark those areas using rects, circles, sprites or masks (see here and here) that you can check against. That is usually much faster. These do not have to be drawn and so would be invisible. They would just be used to mark areas for the collision check.

If you do not know exactly where the colors are in the background or the other images, you can create masks based on the colors in them using pygame.mask.from_surface() or pygame.mask.from_threshold() (docs here and here).

Upvotes: 1

Related Questions