python - Python/Pygame 中的弹性碰撞

标签 python pygame physics

我在处理重力场中的弹性碰撞时遇到了严重的问题。我试图按照能量守恒定律来实现这一点,但它出错了,as shown in this video .首先,两个物体粘在一起,碰撞后数百帧,它们达到了惊人的速度。

complete code is online here ,但是负责在碰撞后给出输出速度的方法是 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)

最佳答案

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

关于python - Python/Pygame 中的弹性碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12392263/

相关文章:

python - 如何在 MacOS Sierra 上安装 pymssql

Python套接字等待

java - 移动人工智能的最佳方式是什么? LibGDX - PONG 游戏

c++ - 子弹物理盒不旋转

python - 我们可以安装带有 enthought canopy 的 pygame 包吗?

java - 角度约束不适用于某些角度

Python:检查列表a中的索引是否=输入=列表b中的索引

python - '{ :08b}' . format(i) 等效于 Python 2.x

python - 特定格式的数据框枢轴

python - Pygame:改变游戏分辨率