python - Graphics.py circle won't bounce off walls
问题描述
I am trying to get a ball to bounce off of the walls of my bounds. Currently, my circle is supposed to hit the wall and then change velocities and move in the opposite direction but this is not happening. I would appreciate some help :) Thank you
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()
解决方案
Several things that may affect the problem.
You should set your velocities once, as you're doing in the first lines in the while loop. Whenever it bounces you should move in the opposite direction using
vel_x = -vel_x
andvel_y = -vel_y
.Right now you're updating both of velocities which might lead to some wierd bounces when only one of the centeres hits a wall.
It might be more logical to check wether the distance from the center to the wall is less than the radius of the circle. This will prevent the issue when the ball moves from
x=599
tox=601
in one iteration, skipping the if statement. (This would also make it so that the circle bounces when its edge hits the wall instead of the center)
- Currently you're only checking 2 walls, unless you meant to do this you should add the if statements for the other walls aswell.
- Small other thing, the second time you draw the random velocities you draw from the range 30 to -30, which is invalid.
推荐阅读
- react-native - 如何基于 git-tag 自动化 react-native ios 应用程序的内部版本号和应用程序版本?
- c# - 每次迭代删除结构列表的有效方法
- c++ - 无法找到没有 WindowName 和 ClassName 的父窗口的子窗口 #32770(对话框)
- ios - 无法选择 tableview 的单元格
- reactjs - React Native - 您当前正在使用 NODE_ENV === "production" 之外的缩小代码
- ios - dSYM 路径 im Azure Pipeline for iOS
- angular - 如何创建 Angular 9 项目?
- python - python中的方法链接导致错误
- datadog - 是否可以将现有数据(如 Prometheus 和 elk 中的数据)迁移到 datadog?
- php - PHP DOM 如何从 UL 获取项目和子项目