简体   繁体   中英

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

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

Then you can use the colliderect function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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