简体   繁体   English

如何使检查矩形碰撞的 if 块仅运行一次?

[英]How do I make an if block that checks for rectangle collisions operate only once?

I am creating a game in pygame where when a player rectangle collides with a green/blue rectangle, they get points.我正在 pygame 中创建一个游戏,当玩家矩形与绿色/蓝色矩形碰撞时,他们会得到分数。 My issue is that when the player collides with the point rectangles, it registers the if block that adds points many times and thus adds way too many points to the points counter, when I only want it to add one point for each blue rectangle and three for each green.我的问题是,当玩家与点矩形碰撞时,它会注册多次添加点的 if 块,从而向点计数器添加太多点,而我只希望它为每个蓝色矩形添加一个点和三个对于每个绿色。 I'll get numbers in the 200s for points, when I should be getting numbers from 0-50.当我应该得到 0-50 的数字时,我会得到 200 多分的数字。

Here is the code that is relevant:这是相关的代码:

blpt = True
gnpt = True
while running:
    #add points if collide with rectangle
    if player_rect.colliderect(bluerect):
        blpt = False
        points += 1
    if player_rect.colliderect(greenrect):
        gnpt = False
        points += 3
    
    #draw point rectangles
    if blpt:
        pygame.draw.rect(screen, "aquamarine3", bluerect)
    if gnpt:
        pygame.draw.rect(screen, "darkolivegreen", greenrect)

I've tried moving the 'add points' if-blocks around in the code, but it doesn't change anything significantly.我试过在代码中移动“添加点”if 块,但它并没有显着改变任何东西。 I need a way to make the if-block operate only once when the collision occurs, turn it into an event somehow, or find some other way that adds only one point to the counter.我需要一种方法让 if 块在碰撞发生时只运行一次,以某种方式将其变成一个事件,或者找到一些其他方法只向计数器添加一个点。

The issue you're having is that the collision code checks every cycle (every time the while loop runs) but the player does not react that quickly.您遇到的问题是碰撞代码会检查每个循环(每次 while 循环运行时),但玩家不会那么快地做出反应。 Normally, you'd handle this sort of thing as an event but you could also do it with a simple Boolean flag for each rectangle:通常,您会将此类事情作为一个事件来处理,但您也可以为每个矩形使用一个简单的 Boolean 标志:

greenCollision = True
blueCollision = True
while running:
    if player_rect.colliderect(bluerect):
        if blueCollision:
            blpt = False
            points += 1
            blueCollision = False
    else:
        blueCollision = True
    if player_rect.colliderect(greenrect):
        if greenCollision:
            gnpt = False
            points += 3
            greenCollision = False
    else:
        greenCollision = True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM