Im making an air hokey game using pygame , but i have no idea how to make the ball bounce in the right direction when the player hits it.
i tried making the ball move in the x direction if the player hits it and if the player is under the ball or aboce it i made it move in the y and x direction but that didnt work
import pygame
import math
pygame.init()
screen = pygame.display.set_mode((800, 400))
background = pygame.image.load("ER.png")
player1 = pygame.image.load("eee.png")
px = 20
py = 148
change = 0
cy = 0
player2 = pygame.image.load("a.png")
px2 = 700
py2 = 148
cx2 = 0
cy2 = 0
ball = pygame.image.load("qw.png")
bx = 351
by = 148
chx = 0
chy = 0
def balls(x,y):
screen.blit(ball,(x,y))
def p1(x, y):
screen.blit(player1,(x , y))
def p2(x, y):
screen.blit(player2,(x , y))
def colid(ex,ey, bx, by):
d = math.sqrt((math.pow(ex - bx, 2)) + (math.pow(by - ey,2)))
if d < 40:
return True
else:
return False
run = True
while run:
screen.blit(background,(0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_d:
change += 1
if event.key == pygame.K_a:
change += -1
if event.key == pygame.K_s:
cy += 1
if event.key == pygame.K_w:
cy += -1
if event.key == pygame.K_LEFT:
cx2 -= 1
print(px2)
print(py2)
if event.key == pygame.K_RIGHT:
cx2 += 1
print(px2)
print(py2)
if event.key == pygame.K_DOWN:
cy2 += 1
print(px2)
print(py2)
if event.key == pygame.K_UP:
cy2 += -1
print(px2)
print(py2)
if event.type == pygame.KEYUP:
if event.key == pygame.K_d:
change -= 1
if event.key == pygame.K_a:
change += 1
if event.key == pygame.K_s:
cy -= 1
if event.key == pygame.K_w:
cy += 1
if event.key == pygame.K_LEFT:
cx2 += 1
if event.key == pygame.K_RIGHT:
cx2 -= 1
if event.key == pygame.K_DOWN:
cy2 -= 1
if event.key == pygame.K_UP:
cy2 += 1
colide = colid(bx, by, px, py)
if colide:
print("colided")
bx += ch
py2 += cy2
px2 += cx2
py += cy
px += change
balls(bx,by)
p1(px,py)
p2(px2, py2)
if px <= -8:
px = -8
if px >= 326:
px = 326
if py <= -8:
py = -8
if py >= 312:
py = 312
if px2 >= 712:
px2 = 712
if py2 <= -8:
py2 = -8
if py2 >= 312:
py2 = 312
if px2 <= 378:
px2 = 378
pygame.display.update()