Pygame Rect Collision

2019-02-25 18:47发布

问题:

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

回答1:

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:

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

Then you can use the colliderect function:

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