gpt4 book ai didi

python - Python/Pygame 中的弹性碰撞

转载 作者:行者123 更新时间:2023-11-28 18:51:24 26 4
gpt4 key购买 nike

我在处理重力场中的弹性碰撞时遇到了严重的问题。我试图按照能量守恒定律来实现这一点,但它出错了,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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com