pygame 移开的矩形留痕迹_Pygame矩形碰撞

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!

Original: https://blog.csdn.net/weixin_36026440/article/details/111952564
Author: 阿野与阿厉
Title: pygame 移开的矩形留痕迹_Pygame矩形碰撞

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/784370/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球