The pong paddle moves so fast that the ball winds up inside the paddle before the collision is detected. The problem is the user input moves the paddle by a single pixel so I don't know how to slow it down. What is the fix? Here is the code:
import pygame, sys, os
from pygame import*
from pygame.locals import*
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
BLUE = (0, 0, 128)
RED = (255,0,0)
os.environ["SDL_VIDEO_CENTERED"]="1"
displaysize=600
DISPLAYSURF = pygame.display.set_mode((displaysize,displaysize))
rectwidth = 50
rectheight= 50
rectposx =0
rectposy =0
class Player(object):
def __init__(self):
self.rect = pygame.rect.Rect((rectposx, rectposy, rectwidth, rectheight))
def handle_keys(self):
key = pygame.key.get_pressed()
dist = 1
if key[pygame.K_LEFT] and (player.rect.x>0):
self.rect.move_ip(-1, 0)
if key[pygame.K_RIGHT] and (player.rect.x<600-rectwidth):
self.rect.move_ip(1, 0)
if key[pygame.K_UP] and (player.rect.y>0):
self.rect.move_ip(0, -1)
if key[pygame.K_DOWN] and (player.rect.y<600-rectheight):
self.rect.move_ip(0, 1)
def draw(self, DISPLAYSURF):
pygame.draw.rect(DISPLAYSURF, BLUE, self.rect)
def postext(self):
pygame.image.load(self.rect).convert_alpha()
pygame.init()
player =Player()
pygame.display.set_caption('Hello World!')
clock=pygame.time.Clock()
fontObj = pygame.font.Font(None,32)
textSurfaceObj = fontObj.render('Hello World!', True, GREEN, BLUE)
#textPosition =
dt=0.1
v = pygame.math.Vector2(5,5)
ballposx=200
ballposy=200
ballrad=10
#DISPLAYSURF.fill(WHITE)
#x=10
#y=10
#dx=5
#rectpos = pygame.Rect(x,y,50,50)
#rect = pygame.draw.rect(DISPLAYSURF, BLUE, rectpos)
pygame.display.update()
running = True
n=0
while running:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
if event.type==QUIT:
pygame.quit()
sys.exit
player.handle_keys()
ballposx=ballposx+v[0]*dt
ballposy=ballposy+v[1]*dt
DISPLAYSURF.fill(WHITE)
DISPLAYSURF.blit(textSurfaceObj,(0,0))
player.draw(DISPLAYSURF)
ball=pygame.draw.circle(DISPLAYSURF, GREEN, (int(ballposx),int(ballposy)), ballrad)
rectposx1=player.rect.x
rectposy1=player.rect.y
rectvelx=-(rectposx-rectposx1)/dt
rectvely=-(rectposy-rectposy1)/dt
if ballposx-ballrad<0:
v[0]=-v[0]
if ballposy-ballrad<0:
v[1]=-v[1]
if ballposx+ballrad>600:
v[0]=-v[0]
if ballposy+ballrad>600:
v[1]=-v[1]
if player.rect.colliderect(ball):
pygame.math.Vector2.reflect_ip(v,-v+5*pygame.math.Vector2(rectvelx,rectvely))
#print (player.rect.x, rectposy, ball.x, ball.y)
ballmass=1
rectmass=5
rectposx=rectposx1
rectposy=rectposy1
print (v)
#raise SystemExit("You win!")
pygame.display.update()
clock.tick(120)