Skip to main content
 首页 » 编程设计

python之Pygame 矩形碰撞

2025年05月04日8zhwl

我正在使用 Python 在 Pygame 中创建一个 Pong 游戏(很明显),并且是 Pygame 的新手,所以希望得到一些帮助来解决当球接触 Racket 时的物理现象,它会反转速度并向相反的方向移动。到目前为止一切正常,但是当球到达 Racket 时,它会直接穿过 Racket 并且不会改变方向。我已经解决了,所以 Racket 不会离开屏幕,球在遇到墙壁时会改变方向,但当球遇到 Racket 时不会改变方向。任何帮助或提示将不胜感激。

我的桨类:

class Paddle:     
    def __init__(self, x, y):     
        self.x = x 
        self.y = y 
        self.height = 40 
        self.width = 10 
 
    def draw(self, canvas): 
         pygame.draw.rect(canvas, pygame.Color(0,0,255),(self.x,self.y,self.width,self.height)) 
    def contains(self, ptX, ptY): 
        return self.x < ptX < self.x + self.width & self.y < ptY < self.y + self.height 
    def overlaps(self, otherRectangle): 
        return otherRectangle.colliderect(Rect(self.x,self.y,self.height, self.width)) 

我的球类

class Ball: 
    def __init__(self, x, y):     
        #position of ball 
        self.x = x 
        self.y = y 
 
        #speed of ball 
        self.dx = 5 
        self.dy = 5 
 
        self.height = 10 
        self.width = 10 
 
    def draw(self, canvas): 
        pygame.draw.rect(canvas, pygame.Color(0,255,0), (self.x,self.y,self.width,self.height)) 
 
    def reset(self): 
        self.x = 320 
        self.y = 240 
 
        self.dx = -self.dx 
        self.dy = 5 

我的目标是让球在接触 Racket 或弹开(重叠点)时反转(负速度)。

请您参考如下方法:

您拥有的代码可能有点过多。让我们来点更简单的。在你的 draw 函数中(在 Ball 和 Paddle 上),继续并让你的线条开始看起来像这样:

self.rect = pygame.draw.rect... 

然后你可以使用colliderect功能:

if ball.rect.colliderect(paddle1): 
    # Reverse, reverse!