以下是我已經糾集了:Python的2D球的碰撞
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
高清的main(): 贏= GraphWin( 「球屏保」,700700)
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()
好吧,這是問題所在。這個數學運作不正常。有時候它可以很好地工作,有時候一個球會壓倒另一個球,或者他們不會像球碰撞那樣反應。我正在努力弄清楚問題所在,但我覺得我現在離項目太近了,看不到它。任何幫助,將不勝感激。
if(bound1.x 0&bound1.y bound3.y)): 你錯過了一些正確的東西?你的幾個if語句就是這樣的 – RamanSB
我相信這是If的。更新了代碼,因爲不管什麼原因,並非我所有的代碼都在那裏。 – Kyle