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

博主正在用Python的Pygame库制作Pong游戏,遇到的问题是当球碰到挡板时,球没有改变方向。已实现挡板保持在屏幕内以及球碰到墙后的反弹,但未处理球与挡板的碰撞。解决方案建议在球和挡板的绘制函数中创建rect对象,并使用colliderect()函数检测碰撞,从而反转球的速度。
摘要由CSDN通过智能技术生成

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!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值