我在pygame中打乒乓球,但我有问题。当球与桨碰撞时,它不会从球上反弹。这是我的代码:
主文件:
import pygame as py
import game_functions as gf
from game_objects import Platform, Platform2, Ball
from settings import Settings
def run_game():
py.init()
ai_settings = Settings()
screen = py.display.set_mode((
ai_settings.screen_width, ai_settings.screen_height
))
py.display.set_caption('Pong')
platform = Platform(ai_settings, screen)
platform2 = Platform2(ai_settings, screen)
ball = Ball(ai_settings, screen)
while True:
gf.check_events(platform, platform2, ball)
platform.update(), platform2.update(), ball.update()
gf.collide_check(ball, platform, platform2, ai_settings)
gf.update_screen(ai_settings, screen, platform, platform2, ball)
run_game()
球类:
class Ball:
def __init__(self, ai_settings, screen):
self.ai_settings = ai_settings
self.screen = screen
self.screen_rect = screen.get_rect()
self.image = py.image.load('pics/ball.png')
self.rect = self.image.get_rect()
self.rect.centerx = self.screen_rect.centerx
self.rect.centery = self.screen_rect.centery
self.moving = False
def update(self):
if self.moving:
self.rect.centerx -= self.ai_settings.ball_speed
def draw_ball(self):
self.screen.blit(self.image, self.rect)
这是我改变方向的功能:
def collide_check(ball, platform, platform2, ai_settings):
if ball.rect.colliderect(platform.rect):
ball.rect.centerx += ai_settings.ball_speed
elif ball.rect.colliderect(platform2.rect):
ball.rect.centerx -= ai_settings.ball_speed
非常感谢您的帮助:/
P.S。如果按下任何用于划水移动的键,则移动标志self.moving
将变为true
。
答案 0 :(得分:0)
您的更新功能未完全完成,因为您需要添加:
def update(self):
self.collide_check(ball, platform, platform2, ai_settings)
if self.moving:
self.rect.centerx -= self.ai_settings.ball_speed
这样你的代码就会更新球的方向。由于它现在位于更新部分,因此每次更新周期发生时都会检查是否存在冲突。 因此,您可能需要添加
collide_check()
进入球类的功能。 我还要补充一点:
if ball.rect.colliderect(platform.rect):
ball.rect.centerx += ai_settings.ball_speed
应改为:
if ball.rect.colliderect(platform.rect):
ai_settings.ball_speed * -1
这样它使ai_settings.ball_speed朝相反的方向发展,因为n * -1 = -1且-n * -1 = 1.