我想使球从边界墙弹起。目前,我的圈子应该撞墙,然后改变速度并朝相反的方向移动,但这并没有发生。我将不胜感激:)谢谢
from graphics import*
from random import*
from time import*
win = GraphWin('My Program', 600, 600)
win.setBackground('pink')
my_circle = Circle(Point(200,300),30)
my_circle.setFill('blue')
my_circle.setOutline('darkorchid1')
my_circle.draw(win)
key = win.checkKey()
while key == '':
vel_x = randint(-30,30)
vel_y = randint(-30,30)
my_circle.move(vel_x, vel_y)
sleep(0.1)
for bounce in range(600):
find_center = my_circle.getCenter()
center_x = find_center.getX()
center_y = find_center.getY()
if center_x == 600 or center_y == 600:
vel_x = -randint(30,-30)
vel_y = -randint(30,-30)
my_circle.move(vel_x, vel_y)
sleep(0.1)
key = win.checkKey()
可能影响问题的几件事。
你应该设置一次速度,就像在while循环的第一行中所做的那样。每当它弹起时,你都应该使用vel_x = -vel_x
和朝相反的方向移动vel_y = -vel_y
。
现在,你正在更新两种速度,当只有一个中心碰到墙壁时,这可能会导致一些奇怪的反弹。
检查从中心到墙壁的距离是否小于圆的半径可能更合乎逻辑。这样可以避免球在一次迭代中从x=599
移到x=601
时跳过if语句的问题。(这也可以使圆在边缘碰到墙而不是中心时反弹)