以下是我的观点:
from graphics import *
from random import *
from math import *
class Ball(Circle):
def init(self, win_width, win_high, point, r, vel1, vel2):
Circle.init(self, point, r)
self.width = win_width
self.high = win_high
self.vecti1 = vel1
self.vecti2 = vel2
def collide_wall(self):
bound1 = self.getP1()
bound2 = self.getP2()
if (bound2.y >= self.width):
self.vecti2 = -self.vecti2
self.move(0, -1)
if (bound2.x >= self.high):
self.vecti1 = -self.vecti1
self.move(-1, 0)
if (bound1.x <= 0):
self.vecti1 = -self.vecti1
self.move(1, 0)
if (bound2.y <= 0):
self.vecti2 = -self.vecti2
self.move(0, 1)
def ball_collision(self, cir2):
radius = self.getRadius()
radius2 = cir2.getRadius()
bound1 = self.getP1()
bound3 = cir2.getP1()
center1 = Point(radius + bound1.x,radius + bound1.y)
center2 = Point(radius2 + bound3.x,radius2 + bound3.y)
centerx = center2.getX() - center1.getX()
centery = center2.getY() - center1.getY()
distance = sqrt((centerx * centerx) + (centery * centery))
if (distance <= (radius + radius2)):
xdistance = abs(center1.getX() - center2.getX())
ydistance = abs(center1.getY() - center2.getY())
if (xdistance <= ydistance):
if ((self.vecti2 > 0 & bound1.y < bound3.y) | (self.vecti2 < 0 & bound1.y > bound3.y)):
self.vecti2 = -self.vecti2
if ((cir2.vecti2 > 0 & bound3.y < bound1.y) | (cir2.vecti2 < 0 & bound3.y > bound1.y)):
cir2.vecti2 = -cir2.vecti2
elif (xdistance > ydistance):
if ((self.vecti1 > 0 & bound1.x < bound3.x) | (self.vecti1 < 0 & bound1.x > bound3.x)):
self.vecti1 = -self.vecti1
if ((cir2.vecti1 > 0 & bound3.x < bound1.x) | (cir2.vecti1 < 0 & bound3.x > bound1.x)):
cir2.vecti1 = -cir2.vecti1
def main():
win = GraphWin("Ball screensaver", 700,700)
velo1 = 4
velo2 = 3
velo3 = -4
velo4 = -3
cir1 = Ball(win.getWidth(),win.getHeight(),Point(50,50), 20, velo1, velo2)
cir1.setOutline("red")
cir1.setFill("red")
cir1.draw(win)
cir2 = Ball(win.getWidth(),win.getHeight(),Point(200,200), 20, velo3, velo4)
cir2.setOutline("blue")
cir2.setFill("blue")
cir2.draw(win)
while(True):
cir1.move(cir1.vecti1, cir1.vecti2)
cir2.move(cir2.vecti1, cir2.vecti2)
time.sleep(.010)
cir1.collide_wall()
cir2.collide_wall()
cir1.ball_collision(cir2)
#cir2.ball_collision(cir1)
main()
好的,这就是问题所在。这个数学根本无法正常工作。有时它很有效,有时候一个球会超过另一个球,或者他们没有像球碰撞那样反应。我正在绞尽脑汁试图弄清问题是什么,但我觉得我现在太接近项目了。任何帮助将不胜感激。
答案 0 :(得分:0)
修复“if”语句是合法且直截了当的。我想你可能会试着说出类似下面的内容。很难说,因为你没有记录你的代码。
if cir2.vecti2 > 0 and bound3.y > bound1.y:
cir2.vecti2 = -cir2.vecti2
请注意,bound3没有值。你会发现其他问题,我敢肯定。
我建议您备份并尝试增量编码。首先,尝试让一个球合法移动,从墙上弹起。放入跟踪位置的打印报表,并标记它们,以便知道您在代码中的位置。
一旦你有了工作,然后添加第二个球。继续打印报表,评论出您认为不再需要的报表。在整个程序运行之前,请不要删除它们。
这会让你前进吗?