Pygame 矩形碰撞

3 投票
2 回答
17491 浏览
提问于 2025-04-18 02:44

我正在用Python和Pygame制作一个乒乓球游戏,因为我对Pygame还不太熟悉,所以想请教一下关于物理方面的问题。当球碰到球拍时,它应该反向并朝相反的方向移动。目前一切都运作得不错,但当球接近球拍时,它却直接穿过球拍,没有改变方向。我已经解决了球拍不会离开屏幕的问题,球在碰到墙壁时会改变方向,但在碰到球拍时却没有。希望能得到一些帮助或建议。

我的球拍类:

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

我的目标是当球碰到球拍或反弹时,球的速度要反向(变成负速度)。

2 个回答

0

关于碰撞检测,可以使用下面的代码,但要记得修改变量。

如果 paddle1 和 paddle2 发生碰撞,也就是它们重叠了,就可以用这个判断:

如果 paddle1.colliderect(paddle2) 或者 paddle2.colliderect(paddle1):

这段代码是用来改变小球在 x 轴上的方向的,具体做法是:

ballDirectionX *= -1

2

你现在的代码可能有点复杂。我们可以用更简单的方法来处理。在你的 draw 函数里(无论是 Ball 还是 Paddle),可以把代码的开头改成这样:

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

然后你可以使用 colliderect 这个函数:

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

撰写回答