如何在pygame中为我的乒乓游戏添加碰撞探测器

时间:2016-05-16 20:39:03

标签: python python-3.x pygame pong

我无法让碰撞检测器为我的乒乓球游戏工作而无需更改所有类(精灵,渲染)。

我在StackOverflow上看到了一些有用的线程,但我似乎无法让它们工作。

#Create a class named sprite to use for the paddles and the ball.
class Sprite():
    def __init__(self,x,y,width,height,color):

        self.x = x

        self.y = y

        self.width = width

        self.height = height

        self.color= (255,255,255)
#attirbute for drawing the sprite(s) to the screen
    def render(self):
        pygame.draw.rect(screen,self.color,(self.x,self.y,self.width,self.height))
 #Create the sprites       
Paddle1 = Sprite(50,175,25,150,color[0])
Paddle2 = Sprite(650,175,25,150,color[1])
Ball = Sprite(300,250,25,25, color[2])
#Set the Sprite's color(s)
Paddle1.color = color[0]
Paddle2.color = color[1]
Ball.color = color[2]
#Variables used for moving the paddles
moveY1,moveY2=0,0
#### Spot where my collision detector goes####

#### Code for drawing and moving the paddles####
    Paddle1.y += moveY1
    Paddle1.render()
    Paddle2.y += moveY2
    Paddle2.render()
    #Draw the Ball
    Ball.render()

1 个答案:

答案 0 :(得分:0)

这是我用pygame制作的Pong游戏的工作片段。我也为第二个保险杠做了,但是为了节省空间而省略了,因为它几乎是同样的事情

def check_bumpers_collision(self):
    if (self.ball.pos_x < self.bumper_one.pos_x + self.bumper_one.width and
        self.ball.pos_x + self.ball.size > self.bumper_one.pos_x and
        self.ball.pos_y < self.bumper_one.pos_y + self.bumper_one.height and
        self.ball.pos_y + self.ball.size > self.bumper_one.pos_y):
        # Change Ball X moving direction
        self.ball.speed_x *= -1
        # Change Y ball Speed
        if self.bumper_one.moving_up:
            self.ball.speed_y -= 5
        elif self.bumper_one.moving_down:
            self.ball.speed_y += 5