Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

python - rect collision with list of rects

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:
    # [...]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...