【发布时间】:2016-04-08 00:39:35
【问题描述】:
所以我正在编写一个斯诺克游戏,我决定找出如何让球相互碰撞的最佳方法是在一个单独的程序中这样做,然后将其复制进去。我是一位非常称职的数学家,所以我坐下来,绘制了事件并计算了实际发生的事情。
我的方法是将每个球的初始速度分解为 xr 和 yr 分量,在其中 xr 分量与通过每个球中心的向量一致的参考系中,以及 yr 分量与此垂直。然后,我对球的 xr 分量进行简单切换,并保持 yr 分量不变,然后计算速度的 x 和 y 分量回到标准参考系中。
出于某种原因,无论是通过数学还是编程错误,我似乎都无法让它工作。以下是我到目前为止所拥有的内容,并且我已经查看了互联网上我能找到的几乎所有相关页面以及在该网站上提出的所有类似问题。我也不是一个精通的程序员。
from visual import *
dt = 0.01
r = 5
red = sphere(pos=(-25,25,0),radius = r,color=color.red)
green = sphere(pos=(25,-25,0),radius = r,color=color.green)
red.velocity = vector(10,-10,0)
green.velocity = vector(-10,10,0)
def posupdate(ball):
ball.pos = ball.pos + ball.velocity*dt
def ballhit(ball1,ball2):
v1 = ball1.velocity
v1x = ball1.velocity.x
v1y = ball1.velocity.y
v2 = ball2.velocity
v2x = ball2.velocity.x
v2y = ball2.velocity.y
xaxis = vector(1,0,0)
btb = ball2.pos - ball1.pos
nbtb = btb/abs(btb)
if abs(btb) < 2*r:
phi = acos(dot(nbtb,xaxis)/abs(nbtb)*abs(xaxis))
ang1 = acos(dot(v1,xaxis)/abs(v1)*abs(xaxis))
ang2 = acos(dot(v2,xaxis)/abs(v2)*abs(xaxis))
v1xr = abs(v1)*cos((ang1-phi))
v1yr = abs(v1)*sin((ang1-phi))
v2xr = abs(v2)*cos((ang2-phi))
v2yr = abs(v2)*sin((ang2-phi))
v1fxr = v2xr
v2fxr = v1xr
v1fyr = v1yr
v2fyr = v2yr
v1fx = cos(phi)*v1fxr+cos(phi+pi/2)*v1fyr
v1fy = sin(phi)*v1fxr+sin(phi+pi/2)*v1fyr
v2fx = cos(phi)*v2fxr+cos(phi+pi/2)*v2fyr
v2fy = sin(phi)*v2fxr+sin(phi+pi/2)*v2fyr
ball1.velocity.x = v1fx
ball1.velocity.y = v1fy
ball2.velocity.x = v2fx
ball2.velocity.y = v2fy
return ball1.velocity, ball2.velocity
while 1==1:
rate(100)
posupdate(red)
posupdate(green)
ballhit(red,green)
提前感谢您提供的任何帮助。
编辑:碰撞检测没有问题,只是计算碰撞后球的速度矢量。抱歉,我应该说得更清楚。
【问题讨论】:
-
大多数情况下,球的方向是错误的。有一小部分,例如仅沿 X 轴的运动可以正常工作,但通常排斥的方向是错误的。
标签: python math collision vpython billiards