rect collision with list of rects

走远了吗. 提交于 2021-01-30 09:05:24

问题


I have the code player_rect.colliderect(tile_rects): where player_rect is a single Rect, and tile_rects is a list of Rects.
I get the error `builtins.TypeError:

Argument must be rect style object

when I try to run my code (presumably as the code doesn't like having a list of rects over a single rect).

I also just found out than when I switch the positions of tile_rects and player_rectI instead get the error

builtins.AttributeError: 'list' object has no attribute 'colliderect'

My question is, how can I change my code so that I can check for collisions with a rect and a list of rects?


回答1:


Use pygame.Rect.collidelist to test whether a rectangle collides with one of a list of rectangles.

collidelist:

Test whether the rectangle collides with any in a sequence of rectangles. The index of the first collision found is returned. If no collisions are found an index of -1 is returned.

if player_rect.colliderect(tile_rects) >= 0:
    # [...]



回答2:


you may use a for loop:

for t in tile_rects:
    player_rect.colliderect(t)

if you want to check for any collision you may use:

has_colide = any(player_rect.colliderect(t) for t in tile_rects)


来源:https://stackoverflow.com/questions/61007064/rect-collision-with-list-of-rects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!