You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pygame中两个移动Rect碰撞检测持续误触发如何解决

问题根因

你的碰撞检测逻辑和坐标更新逻辑完全脱节,pygame的Rect对象不会自动同步你自定义的x/y/ex/ey变量的值,你每次修改坐标后都要手动更新两个Rect的位置,否则碰撞检测一直用的是两个Rect初始化时的默认左上角坐标(0,0),自然会持续误报碰撞。

其他需要修正的错误

  • 按键事件处理缩进错误:KEYDOWN判断写在了事件遍历循环外部,只能拿到最后一个触发的事件,且向右移动的x += 4代码行没有正确缩进,会直接触发语法错误
  • 敌方单位y坐标增量ey += 2的缩进错误,和主循环层级不一致
  • 碰撞判断的位置错误:你在更新坐标之前就执行了碰撞检测,每次判断的都是上一帧的位置,会出现碰撞检测延迟

修正后可运行代码

import pygame
import sys
import random
pygame.init()

size = width, height = 800, 600
white = 255, 255, 255
clock = pygame.time.Clock()

screen = pygame.display.set_mode(size)

character = pygame.image.load("intro_ball.gif")
charrect = character.get_rect()
x = 340
y = 480

enemy = pygame.image.load("ho.png")
enrect = enemy.get_rect()
ex = random.randint(0, 690)
ey = 0
lose = False

while 1:
    clock.tick(60)
    # 事件处理统一放在循环内
    for event in pygame.event.get():
        if event.type == pygame.QUIT: 
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT and x < 690:
                x += 4
            if event.key == pygame.K_LEFT and x > 0:
                x -= 4

    if ey >= 600 and not lose:
        ey = 0
        ex = random.randint(0, 690)
    
    # 坐标更新完成后同步到Rect对象
    charrect.topleft = (x, y)
    enrect.topleft = (ex, ey)
    # 再执行碰撞检测
    collide = pygame.Rect.colliderect(charrect, enrect)

    if collide:
        lose = True
    else: 
        lose = False

    if lose: 
        print("lose")

    ey += 2        
    screen.fill(white)
    screen.blit(enemy, (ex, ey))
    screen.blit(character, (x, y))
    pygame.display.update()

内容的提问来源于stack exchange,提问作者FireFlower

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 21:45:05