Pygame矩形碰撞 [英] Pygame Rect Collision

查看:1445
本文介绍了Pygame矩形碰撞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Python在Pygame中创建一个Pong游戏(显然),并且是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.

我的桨式课程:

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

我的球类

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

推荐答案

你的代码可能是一个少过多。让我们去一些更简单的东西。在绘制函数( Ball & Paddle ),继续并使你的行的开头看起来像这样:

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

然后您可以使用 colliderect function:

Then you can use the colliderect function:

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

这篇关于Pygame矩形碰撞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆