Pygame矩形碰撞

2024-06-12 03:28:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用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

我的目标是当球碰到球拍或反弹(重叠点)时,使球的速度反向(负速度)。


Tags: rectselfinitdefwidthpygame速度class
1条回答
网友
1楼 · 发布于 2024-06-12 03:28:13

你的代码可能有点过分。让我们做些更简单的事情。在draw函数(在Ball&;Paddle上)中,继续并使行的开头看起来如下:

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

然后可以使用colliderect函数:

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

相关问题 更多 >