Changing the ball_y_change or ball_x_change values to anything under 0 will make the ball stuck and not move. I've tried changing the values of the variables from 0 - 0.9 and none of them have worked. Can anyone provide a solution to this or help me make the ball slower so that you can actually see where the ball is going?
import pygame
import sys
def ball_animation(ball_x_change, ball_y_change):
pass
def collision(player1, player2, ball):
collide1 = pygame.Rect.colliderect(player1, ball)
collide2 = pygame.Rect.colliderect(player2, ball)
if collide1:
print("hi")
if collide2:
print("hello")
pygame.init()
width = 1000
height = 600
screen = pygame.display.set_mode((width, height))
# Rectangles
player1 = pygame.Rect(20, 200, 15, 140)
player1_y_change = 0
player2 = pygame.Rect(965, 200, 15, 140)
player2_y_change = 0
ball = pygame.Rect(width/2 - 15, height/2 - 15, 30, 30)
ball_x_change = 0.6
ball_y_change = 0.6
while True:
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
player1_y_change = -1
if event.key == pygame.K_s:
player1_y_change = 1
if event.key == pygame.K_i:
player2_y_change = -1
if event.key == pygame.K_k:
player2_y_change = 1
if event.type == pygame.KEYUP:
if event.key == pygame.K_w or event.key == pygame.K_s:
player1_y_change = 0
if event.key == pygame.K_i or event.key == pygame.K_k:
player2_y_change = 0
# Player 1 Boundaries
player1.y += player1_y_change
if player1.y <= 10:
player1.y = 10
elif player1.y >= 450:
player1.y = 450
# Player 2 Boundaries
player2.y += player2_y_change
if player2.y <= 10:
player2.y = 10
elif player2.y >= 450:
player2.y = 450
# Ball Boundaries
ball.x += ball_x_change
ball.y += ball_y_change
if ball.y <= 0:
ball_y_change *= -1
elif ball.y >= 570:
ball_y_change *= -1
elif ball.x < 0 or ball.x > 970:
ball.x = width/2 - 15
ball.y = height/2 - 15
pygame.draw.rect(screen, (200, 200, 200), (player1))
pygame.draw.rect(screen, (200, 200, 200), (player2))
pygame.draw.ellipse(screen, (200, 200, 200), (ball))
collision(player1, player2, ball)
pygame.display.update()