碰撞检测工作正常,但分数飙升,因为发生了多次碰撞。 (pygame)

The collision detection works fine, but the score skyrockets, because multiple collisions occur. (pygame)

在壁球比赛中(类似于乒乓球,但有一个玩家,球从墙上弹起。)我对球和球拍进行了碰撞检测,当它们碰撞时得分加 1。我有一个碰撞问题:当球击中桨的顶部或底部时,它会像这样 https://i.imgur.com/w2DrOft.gif . I fixed that with ball.vx = -abs(ball.vx), and it looks like this now: https://i.imgur.com/6duDp6g.gif 。虽然碰撞和弹跳效果很好,但当发生顶部或底部碰撞时,分数会立即高出几个数字。如果你只看到碰撞而忽略分数,它根本不明显,但更多的碰撞同时发生并且分数飙升。

hits = 0 

font = pygame.font.Font('freesansbold.ttf',25)
def Objects(paddle,ball,hits,font,black):
    temp = hits

  if ball.BallRect.colliderect(paddle.PaddleRect):
  
          ball.vx = -abs(ball.vx)
      
          score_text = font.render(f"Score: " + str(hits + 1),True, black)
          temp += 1 
  else: 
          score_text = font.render(f"Score: " + str(hits),True, black)
          window.blit(score_text,(20,20))

   return temp
 
  done = False 
  while not done: 
      hits = Objects(paddle,ball,hits,font,black=
      pygame.display.update() 
    
      clock.tick(120)

如何确定分数?

只有当球向右移动时才增加分数。这意味着只有当 ball.vx 大于 0 时,分数才会增加。你需要在改变球的方向之前(在改变 ball.vx 之前)这样做:

def Objects(paddle, ball, hits, font, black):

    if ball.BallRect.colliderect(paddle.PaddleRect):
  
          if ball.vx > 0:
              hits += 1
          ball.vx = -abs(ball.vx)
      
    score_text = font.render(f"Score: " + str(hits), True, black)
    window.blit(score_text, (20, 20))

    return hits