简体   繁体   English

Pygame 矩形碰撞

[英]Pygame Rect Collision

I am creating a game of Pong in Pygame with Python (obviously) and am new to Pygame so would like some help working the physics of when the ball touches the paddle, it will reverse speeds and go the opposite direction.我正在使用 Python 在 Pygame 中创建 Pong 游戏(显然)并且我是 Pygame 的新手,所以想要一些帮助来处理球接触球拍时的物理学,它会反转速度并朝着相反的方向前进。 Everything works so far, but when the ball goes to the paddle, it goes right through it and does not change direction.到目前为止一切正常,但是当球到达桨时,它会直接穿过它并且不会改变方向。 I have it worked out so the paddles do not leave the screen and the ball changes direction when it meets a wall, but not when the ball meets a paddle.我已经解决了,所以桨不会离开屏幕,当球碰到墙壁时会改变方向,但当球碰到桨时不会改变方向。 Any help or tips would be appreciated.任何帮助或提示将不胜感激。

My paddle class:我的桨类:

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))

My ball class我的球类

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

My goal is to have the speed of the ball reverse (negative speed) when it touches the paddle or bounces off (overlapping points).我的目标是让球在接触球拍或反弹(重叠点)时的速度反向(负速度)。

The code that you have is probably a little excessive.您拥有的代码可能有点过分。 Let's go with something a bit more simple.让我们来点更简单的事情。 Within your draw functions (on both Ball & Paddle ), go ahead and make the start of your lines look like this:在你的draw函数中(在BallPaddle ),继续让你的线条的开始看起来像这样:

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

Then you can use the colliderect function:然后你可以使用colliderect函数:

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

For the collision use the code below but change the variables对于碰撞使用下面的代码但更改变量

If paddle1.colliderect(paddle2) or paddle2.colliderect(paddle1): That is the ball direction in the x-axis ballDirectionX*=-1如果paddle1.colliderect(paddle2)或paddle2.colliderect(paddle1):即x轴球方向ballDirectionX*=-1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM