Warm tip: This article is reproduced from serverfault.com, please click

python-Graphics.py圈子不会反弹

(python - Graphics.py circle won't bounce off walls)

发布于 2020-11-29 23:22:54

我想使球从边界墙弹起。目前,我的圈子应该撞墙,然后改变速度并朝相反的方向移动,但这并没有发生。我将不胜感激:)谢谢

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()
Questioner
lizzie_lolz
Viewed
0
IsolatedSushi 2020-11-30 08:00:51

可能影响问题的几件事。

  1. 你应该设置一次速度,就像在while循环的第一行中所做的那样。每当它弹起时,你都应该使用vel_x = -vel_x朝相反的方向移动vel_y = -vel_y

  2. 现在,你正在更新两种速度,当只有一个中心碰到墙壁时,这可能会导致一些奇怪的反弹。

  3. 检查从中心到墙壁的距离是否小于圆的半径可能更合乎逻辑。这样可以避免球在一次迭代中x=599移到x=601时跳过if语句的问题。(这也可以使圆在边缘碰到墙而不是中心时反弹)

  1. 当前,你仅检查2面墙,除非你打算这样做,否则还应为其他墙添加if语句。
  1. 另外,第二次绘制随机速度的范围是30到-30,这是无效的。