3

我在处理引力场中的弹性碰撞时遇到了一个严重的问题。我试图按照能量守恒定律来实现这一点,但它出错了,如本视频所示。首先,两个物体粘在一起,碰撞后几百帧,它们达到了巨大的速度。

完整的代码在这里在线,但是负责在碰撞后给出输出速度的方法是这个函数来自world.py

def collision(self, obj1, obj2):
    R = obj1.radius + obj2.radius   # code is used to "jump back in time" to avoid penetration when there's a collision
    dx = obj1.x - obj2.x            #
    dy = obj1.y - obj2.y            #
    K = math.hypot(dx, dy)          #   
    dvx = obj1.vx - obj2.vx         #   
    dvy = obj1.vy - obj2.vy         #
    dv = math.hypot(dvx, dvy)       #
    deltat = (R - K)/dv             #
    print dv
    print deltat
    obj1.x = obj1.rect.centerx = obj1.x - obj1.vx # *deltat
    obj2.x = obj2.rect.centerx = obj2.x - obj2.vx # *deltat
    obj1.y = obj1.rect.centery = obj1.y - obj1.vy # *deltat
    obj2.y = obj2.rect.centery = obj2.y - obj2.vy # *deltat
    dx = obj2.x - obj1.x
    dy = obj2.y - obj1.x
    delta = math.hypot(dx, dy)
    nx = dx/delta
    ny = dy/delta
    vx1bc = obj1.vx * nx
    vx2bc = obj2.vx * nx
    vy1bc = obj1.vy * ny
    vy2bc = obj2.vy * ny
    vx2ac = (obj2["energy_loss"]*(vx1bc - vx2bc) + vx1bc + (obj2["mass"]/obj1["mass"]*vx2bc))/((obj2["mass"]/obj1["mass"])+1)
    vy2ac = (obj2["energy_loss"]*(vy1bc - vy2bc) + vy1bc + (obj2["mass"]/obj1["mass"]*vy2bc))/((obj2["mass"]/obj1["mass"])+1)
    vx1ac = (vx1bc + obj2["mass"]/obj1["mass"]*vx2bc - obj2["mass"]/obj1["mass"]*vx2ac)*obj1["energy_loss"]
    vy1ac = (vy1bc + obj2["mass"]/obj1["mass"]*vy2bc - obj2["mass"]/obj1["mass"]*vy2ac)*obj1["energy_loss"]
    V1cx = obj1.vx * ny
    V1cy = obj1.vy * ny
    V2cx = obj2.vx * ny
    V2cy = obj2.vy * ny
    alfa = math.atan2(ny, nx)
    alfa_deg = math.degrees(alfa)
    v1a = math.hypot(vx1ac, vy1ac)
    v2a = math.hypot(vx2ac, vy2ac)
    obj1.vx = v1a*math.cos(alfa)+V1cx * math.sin(alfa)
    obj2.vx = v2a*math.cos(alfa)+V2cx * math.sin(alfa)
    obj1.vy = v1a*math.sin(alfa)+V1cx * math.cos(alfa)
    obj2.vy = v2a*math.sin(alfa)+V2cx * math.cos(alfa)
4

1 回答 1

1

您的代码使用了许多不同的变量,而且它们的名称也不那么相关。这使得很难跟上所有的东西,也很难让其他人看到你的程序做了什么。也许您应该将变量附加到列表并访问它们?另外我建议你看看一个很棒的物理教程: http ://www.petercollingridge.co.uk/pygame-physics-simulation

于 2012-09-15T07:30:23.607 回答