击中"wall"时如何在pygame中改变圆的方向



我想知道如何改变一个正方形的方向,当它撞到墙"pygame。下面是我的代码:

"""
Date: Nov 4, 2020
Description: Animating Shapes with pygame
"""

import pygame

def main():
'''This function defines the 'mainline logic' for our game.'''
# I - INITIALIZE
pygame.init()
# DISPLAY
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Crazy Shapes Animation")
# ENTITIES
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((255, 255, 255))  # white background
# Make a red 25 x 25 box
red_box = pygame.Surface((25, 25))
red_box = red_box.convert()
red_box.fill((255, 0, 0))
# A - ACTION (broken into ALTER steps)
# ASSIGN
clock = pygame.time.Clock()
keepGoing = True
red_box_x = 0  # Assign starting (x,y)
red_box_y = 200  # for our red box
# LOOP
while keepGoing:
# TIMER
clock.tick(30)
# EVENT HANDLING
for event in pygame.event.get():
if event.type == pygame.QUIT:
keepGoing = False
# change x coordinate of box
red_box_x += 5
# check boundaries, to reset box to left-side
if red_box_x > screen.get_width():
red_box_x = 0
# REFRESH (update window)
screen.blit(background, (0, 0))
screen.blit(red_box, (red_box_x, red_box_y))  # blit box at new (x,y) location
pygame.display.flip()
# Close the game window
pygame.quit()

# Call the main function
main()

当它撞到最右边的墙时,我想让它反转方向,回到最左边的墙。然后它继续无限地撞击墙壁。这是学校的作业,我在网上找不到任何解决方案,所以如果你能帮我的话就太好了!

为移动(move_x)使用变量而不是常量。当对象撞墙时,反转变量(move_x *= -1)的值:

def main():
# [...]
move_x = 5
# LOOP
while keepGoing:
# [...]
# change x coordinate of box
red_box_x += move_x
# check boundaries, to reset box to left-side
if red_box_x >= screen.get_width():
red_box_x = screen.get_width()
move_x *= -1
if red_box_x <= 0:
red_box_x = 0
move_x *= -1
# [...]

最新更新