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

Pygame开发问题:碰撞无敌帧代码为何从未执行到第二个print语句?

问题原因分析
  • 变量作用域错误:你当前把anticolision定义为碰撞检测逻辑内的局部变量,每次主循环执行到碰撞检测段都会被重新赋值为False,上一循环设置的无敌状态会被直接清空,根本无法保留到下一帧。
  • 时间判断逻辑位置错误:你将1秒重置的判断写在了碰撞触发的分支内部,只有发生碰撞的那一帧才会执行这段判断。正常运行时碰撞触发的瞬间,两个时间戳的差值最多只有几毫秒,永远不可能满足>1的条件;只有调试时在碰撞触发处打断点,人为停留超过1秒,差值才会符合要求,这就是仅调试时能触发第二个打印的原因。
  • 时间差计算逻辑错误:你写的espera = (anticolision_time - current_time)/ 1000计算结果为负数,正常运行时永远不可能大于1,就算位置放对也不会触发重置。
修复方案
  1. 将anticolision、anticolision_time改为类的实例属性,在类初始化时赋值,不要在主循环内重复初始化:
# 类的__init__方法中添加
self.anticolision = False
self.anticolision_time = 0
  1. 把无敌状态重置的逻辑移到碰撞检测逻辑外,每次主循环都判断是否到重置时间。
  2. 修正时间差计算,用当前时间减去碰撞发生的时间得到已过的无敌时长。

修正后的参考代码:

current_time = 0
while running :
    current_time = pygame.time.get_ticks() 
    # 先判断无敌状态是否到期
    if self.anticolision:
        espera = (current_time - self.anticolision_time) / 1000
        if espera > 1:
            print("anticolision false")
            self.anticolision = False

    if self.player.estado == self.player.Estado.volando:
        # 碰撞检测
        colisiones = pygame.sprite.spritecollide(self.player, self.asteroides, True, pygame.sprite.collide_circle)
        for colision in colisiones:
            if colision and not self.anticolision:
                self.anticolision_time = pygame.time.get_ticks()
                self.anticolision = True 
                print("anticolision true")                        
                expl = Explosion(colision.rect.center)
                self.explosionSound.play()
                self.all_sprites.add(expl)                  
                self.vidas -= 1

        if self.vidas == 0:     
            self.gameOver()
            running= False

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 12:54:02