python - 如何使用 pygame 检测两个 Sprite 的碰撞?

标签 python pygame sprite collision

这是我到目前为止的代码,我可以移动它并放置一个可以拾取的 blip,我只需要知道如何注册它并将 blip 移动到新的随机位置! 我对 pygame 很陌生,对 python 也不是 100% 流利,但我还不错。如果有适合中级编码员使用 Python 的 pdf:那就太好了!

import sys, pygame, os, math
from random import randint

pygame.init()

size = width, height = 800, 600
speed = [2, 2]
black = 1, 1, 1
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Pick up the squares!')
UP='up'
DOWN='down'
LEFT='left'
RIGHT='right'

ball = pygame.image.load("ball.png")
ballrect = ball.get_rect()
ballx = 400
bally = 300

blip = pygame.image.load("blip.png")
bliprect = blip.get_rect()
blipx = randint(1,800)
blipy = randint(1,600)

background = pygame.Surface(screen.get_size())
background = background.convert()

background.fill((250, 250, 250))


clock = pygame.time.Clock()

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()


    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT]:
        ballx  -= 5
    if keys[pygame.K_RIGHT]:
        ballx += 5
    if keys[pygame.K_UP]:
        bally -= 5
    if keys[pygame.K_DOWN]:
        bally +=5    

    screen.fill(black)
    screen.blit(ball, (ballx,bally))
    screen.blit(blip, (blipx, blipy))
    pygame.display.update()
    clock.tick(40)

最佳答案

使用矩形的colliderect方法:

if ballrect.colliderect(bliprect):
    print 'Do something here'

关于python - 如何使用 pygame 检测两个 Sprite 的碰撞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28488088/

相关文章:

Phaser 中的旋转和 getBounds()

python - 如何从 Pandas 邻接矩阵数据帧创建有向网络图?

Python树实现-节点引用

python - 如何在Python 3.7中使用Pygame显示用Pillow加载的图像?

python - Pygame 碰撞检测不适用于旋转图像

java - 创建具有定义颜色的 JQuery-Sprites

python - 对 csv 文件中的重复值列 A 进行排序

python - 在 Uvicorn 中与多个工作线程一起使用多重处理(线程锁)

python - 音频未加载

python - (Python/Linux) 通过 python 或 os.system 命令无延迟地播放 wav 文件