问题描述
我正在尝试重新创建“ Pong”,并且正在努力找出碰撞的原因。这是代码:
ball_x += ball_x_change
collide = player_collision(player_x,ball_x,player_y,ball_y)
if collide:
ball_x -= ball_x_change
ball(ball_x,ball_y)
这旨在将球从其起始位置移向玩家,并检查玩家图标和球是否发生碰撞。如果有,它将改变球的方向。然后将球渲染到屏幕上。 这就是整个事情:
import pygame
import math
pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Pong")
icon = pygame.image.load("ping-pong.png")
pygame.display.set_icon(icon)
player_icon = pygame.image.load("vertical-line.png")
player_x = 800 - (64 + 32)
player_y = 236
player_y_change = 0
cpu_icon = pygame.image.load("vertical-line.png")
cpu_x = 0 - 32
cpu_y = 236
cpu_y_change = 0
ball_icon = pygame.image.load("oval.png")
ball_x = 384
ball_y = 284
ball_x_change = 0.5
ball_y_change = 0
def player(player_x,player_y):
screen.blit(player_icon,(player_x,player_y))
def cpu(cpu_x,cpu_y):
screen.blit(cpu_icon,(cpu_x,cpu_y))
def ball(ball_x,ball_y):
screen.blit(ball_icon,(ball_x,ball_y))
def player_collision(ball_x,ball_y,player_x,player_y):
bump = math.hypot(player_x - ball_x,player_y - ball_y)
if bump < 20:
return True
else:
return False
running = True
while running:
screen.fill((255,255,255))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
player_y_change += 1
if event.key == pygame.K_UP:
player_y_change -= 1
if event.type == pygame.KEYUP:
if event.key == pygame.K_DOWN or pygame.K_UP:
player_y_change = 0
player_y += player_y_change
if player_y <= 0:
player_y = 0
elif player_y >= 472:
player_y = 472
player(player_x,player_y)
cpu_y += cpu_y_change
if cpu_y <= 0:
player_y = 0
elif player_y >= 472:
player_y = 472
cpu(cpu_x,cpu_y)
ball_x += ball_x_change
collide = player_collision(player_x,ball_y)
pygame.display.update()
感谢您的时间。
更新了代码,但仍然无法使用:
import pygame
import math
pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Pong")
icon = pygame.image.load("ping-pong.png")
pygame.display.set_icon(icon)
player_icon = pygame.image.load("vertical-line.png")
player_x = 672
player_y = 236
player_y_change = 0
cpu_icon = pygame.image.load("vertical-line.png")
cpu_x = 0
cpu_y = 236
cpu_y_change = 0
ball_icon = pygame.image.load("oval.png")
ball_x = 384
ball_y = 284
ball_x_change = 0.8
ball_y_change = 0
def player(player_x,player_y):
touch = math.hypot(player_x - ball_x,ball_y - player_y)
if touch < 10:
return True
else:
return False
running = True
while running:
screen.fill((255,cpu_y)
ball_x += ball_x_change
collide = player_collision(ball_x,player_y)
if collide:
ball_x_change = -ball_x_change
ball_x += ball_x_change
ball(ball_x,ball_y)
pygame.display.update()
解决方法
函数player_collision
在(ball_x,ball_y,player_x,player_y)
中接受其参数,但是在调用该函数时,您按错误的顺序输入了参数
collide = player_collision(player_x,ball_x,player_y,ball_y)
#should be
collide = player_collision(ball_x,player_y)
您还应该执行@RFairey建议的操作并添加ball_x_change *= -1
就像发生碰撞时一样,您只需将球向x后退一步:
register
要反转其方向,您还需要消除ball_x_change,以便在弹跳后沿另一个方向移动:
serve