Search code examples
pythonlistpygamespritecollision-detection

Pygame - How to detect if sprites are in area?


I need a way to get a list of all sprites in a certain area of the screen, and I cannot find one anywhere on the internet.
Can someone please give me an example code of how to do this?

If it helps, all the sprites are in an "active" list.


Solution

  • Depends on whether you have obstacles or not, i.e. what the definition of "In the Area" means and also home many sprites you are dealing with.

    If there's not many sprites and the distance calc is fast then brute force is probably ok.

    for sprite in sprites:
        if something.distance(sprite) < THRESHOLD:
            do_something_with_near_sprite(sprite)
    

    If you have a lot of sprites have a look at quadtrees and things like that. If calculating the distance is complicated then you're probably going to want to look at A* algorithm. There are libraries for these things so you shouldn't have to implement them yourself unless you want to.

    This is a pretty general question (prepare to have it voted down by others :)