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
451 views
in Technique[技术] by (71.8m points)

python - PyGame Collision?

How do I find collisions between characters and images within PyGame? I have drawn a player from an image, and have drawn the walls from tiles, so how would I detect these collisions?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

If you use the pygame Rect class to represent the boundaries of your object, you can detect whether two are colliding by using the Rect.colliderect function. For example:

import pygame

a = pygame.Rect((1, 1), (2, 2))
b = pygame.Rect((0, 0), (2, 2))
c = pygame.Rect((0, 0), (1, 1))
a.colliderect(b)
# 1
a.colliderect(c)
# 0
b.colliderect(c)
# 1

a is colliding with b, and b is colliding with c, but a is not colliding with c. Note that rects that share a boundary are not colliding.

Pygame also supports letting you use a Rect as the position for an image when you want to 'blit' it onto the screen.


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

...