Long post
I can not seem to get my collisions to work in this game of Pong. Along with the collisions, I would really like some help adding physics to the game (ball hits from NE and bounces back at SW)
I have included some of my code for the game. I am having a few issues that could use some debugging. The ball occasionally goes through the paddles, and occasionally gets an invisible wall at aprox. X= 40px.
All help is greatly appreciated.
Thanks in advance
size = (700, 500)
screen = pygame.display.set_mode(size)
done = False
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)
def render(self):
pygame.draw.rect(screen,self.color,(self.x,self.y,self.width,self.height))
Paddle1 = Sprite(50,175,25,150,WHITE])
Paddle2 = Sprite(650,175,25,150,WHITE)
Ball = Sprite(300,250,25,25,WHITE)
moveY1,moveY2 = 0,0
This is all of the code that I have for collisions with the ball.
if Ball.y >= 500 or Ball.y <= 0 :
Ball_move_y *= -1
Ball_move_x *= -1
if Ball.x >= 700 or Ball.x <= 0:
Ball_move_x *= -1
Ball_move_y *= -1
if Ball.x &g= Paddle1.x and Ball.y >= Ball.y and Ball.x <= (Paddle1.x + -50) and Ball.y <= (Paddle1.y + -50):
Ball_move_x *= -1
Ball_move_y *= -1
elif (Ball.x + -50) >= Paddle2.x and (Paddle2.y+ -50) >= Paddle2.y and (Ball.x+ -50) <= (Paddle2.x + -50) and (Ball.y+ -50) <= (Paddle2.y + -50):
Ball_move_x *= -1
Ball_move_y*= -1
This is for moving the actual ball, after it has been drawn to the screen (deleted drawing since it is irrelevant to the question).
Ball.x += Ball_move_x
Ball.y += Ball_move_y
clock.tick(60)
This is the end of the code, minus the quit statement. I'm not sure if the frames per second is relevant to this code.
What I have tried:
I have tried adding a different collision detector, but that seems to make things worse.
After fixing what was pointed out in solutions 1 and 2, my boundaries are working better, but I can not get my paddles to hit my ball.