如何分别定义 x 和 y 的碰撞?

How do I define collisions for x and y separately?

所以在这个函数中,我有一个球和一个球拍之间的碰撞检测和得分(以及与这个问题无关的其他东西)。当球击中球拍时,它会朝相反的方向弹开。它对桨的左侧很有效,但如果球从顶部或底部击中,它就会滑动并且得分会飙升。

def Objects (paddle,ball,hits,font,black):  
    if ball.BallRect.colliderect(paddle.PaddleRect):
        ball.vx *= -1
        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

参见

当小球击中左边球拍时,小球向右弹起,后面的x方向必须为正。当小球击中右球拍时,小球向左弹起,后面的x方向一定是负数。
使用 abs(x) 计算数字的绝对值。球的新方向是 abs(ball.vx)-abs(ball.vx).

你要区分leftPaddlerightPaddle

if ball.BallRect.colliderect( leftPaddle.PaddleRect ):
    ball.vx = abs(ball.vx)

    # [...]

elif ball.BallRect.colliderect( rightPaddle.PaddleRect ):
    ball.vx = -abs(ball.vx)

    # [...]

或者您需要知道击中了哪个球拍。将 "left""right" 传递给参数 side:

def Objects(paddle, side, ball, hits, font, black):  
    if ball.BallRect.colliderect(paddle.PaddleRect):
      
        if side == "left":
            ball.vx = abs(ball.vx)
        else:
            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

如果你只有1个桨,设置正确的方向就足够了。如果你有合适的球拍:

def Objects(paddle, ball, hits, font, black):  
    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