pygame 的崩溃事件

crashing event with pygame

我正在做一个简单的 pygame 项目,它目前有从屏幕顶部飞到屏幕底部的坠落炸弹。如果玩家击中炸弹,他们就会死亡。到目前为止一切正常。问题是当炸弹经过玩家但还没有离开屏幕时,它仍然会杀死玩家。意思是,炸弹会穿过玩家的下半部分,但如果你越过,在它穿过屏幕下半部分之前,你就会死。他是我的代号:

   if player.rect.y < thing_starty + thing_height:
        if player.rect.x > thing_startx and player.rect.x < thing_startx + thing_width or player.rect.x  + 28 > thing_startx and player.rect.x  + 28 < thing_startx + thing_width: 
            gameOver = True

数值如下:

thing_startx = random.randrange(0, S_WIDTH)
thing_starty = -300
thing_speed = 3
thing_width = 128
thing_height = 128

player.rect.x 的值在 120 到 500 之间,具体取决于玩家在屏幕上的位置。 (屏幕也会随着你的移动从左向右滚动。)28来自字符图像的宽度。

坠落物体的代码如下:

if thing_starty > S_HEIGHT:
        pygame.mixer.Sound.play(bomb_sound)
        thing_starty = 0 - thing_height
        thing_startx = random.randrange(0, S_WIDTH)
        dodged += 1
        thing_speed += .5

我已经为此工作了大约一个星期,但没有取得任何进展。感谢您的任何帮助。

我不知道 python 但很明显,您用来测试碰撞的条件语句只是检查 y 值是否大于玩家的 y 值,这将当然,即使它通过屏幕底部也是如此。所以你需要在某处有一个 AND 操作数。

伪代码(因为我不知道python...或者你正在使用的任何东西)

if (bomb.y >= player.y AND bomb.y <= player.y + player.height){
    run bomb hits player logic
}

或者如果你不想使用 AND 操作数(它不会是 AND,但每种语言都有它自己的版本)那么你可以只使用像这样的嵌套条件块

伪代码

if (bomb.y >= player.y){
    if (bomb.y <= player.y + player.height){
        run bomb collision logic
    }
 }

如果炸弹在玩家下方/屏幕外,碰撞逻辑不会运行。当然还需要通过x位置测试,不过你好像已经搞定了

正如 Neal 所说,您只需检查 y 值是否大于玩家的 y 值。

但我的建议是,停止使用这样的代码:

 if player.rect.y < thing_starty + thing_height:
    if player.rect.x > thing_startx and player.rect.x < thing_startx + thing_width or player.rect.x  + 28 > thing_startx and player.rect.x  + 28 < thing_startx + thing_width: 
        gameOver = True

并查看 documentation for the Rect class to find a lot of handy functions, like colliderect

也可以使用 Rect 来表示炸弹的位置*(就像您对 player 所做的那样),您可以使用这样的代码:

if player.rect.colliderect(thing.rect):
    gameOVer = True

* 应该有它自己的 class,继承自 Sprite,但那是另一个话题