我编写了一个 Python 脚本,它创建一个 Ball 类,然后创建它的实例。球应该从墙上反弹,然后(尚未实施)彼此反弹。请注意,当球撞到墙壁时,不是仅仅反转球的方向,而是墙壁对球施加力(或加速度)。
不幸的是,在从墙上弹起后,球会进入振荡运动,幅度越来越大。
我对 Python 很陌生,但之前写过各种 javascript/canvas 模拟。
这个特殊的 python 脚本使用 Verlet 集成来计算位置和速度。我的脚本基于此:
http://physics.weber.edu/schroeder/software/demos/MolecularDynamics.html
任何人都可以建议我应该如何修改代码,使其在球从墙上弹起时“稳定”吗?谢谢
from Tkinter import *
import random
window = Tk()
canvas = Canvas(window, width = 400, height = 300)
canvas.pack()
wallStiffness=0.05
dt=0.02
class Ball:
def __init__(self):
self.x=0
self.y=0
self.xvel=random.random()*2-1
self.yvel=random.random()*2-1
self.ax=0
self.ay=0
self.rad=20
def computeAccelerations(z):
if z.x<z.rad:
z.ax=wallStiffness*(z.rad-z.x)
else:
if z.x>400-z.rad:
z.ax=wallStiffness*(400-z.rad-z.x)
#only have horizontal bounces so far, and no bounces between balls yet
list=[]
for i in range(100): #0 to 99, make 100 balls
myball=Ball()
list.append(myball)
#script to place in a crystal to begin with
current_x=30
current_y=0
for j in list:
j.x=current_x
current_x+=30
j.y=current_y
if current_x+30>370:
current_x=30
current_y+=30
j.ball=canvas.create_oval(j.x,j.y,j.x+j.rad,j.y+j.rad,fill="blue")
while True:
for i in range(10): #10 steps per frame
for j in list:
j.x+=j.xvel*dt+0.5*j.ax*dt*dt
j.y+=j.yvel*dt+0.5*j.ay*dt*dt
j.xvel+=0.5*j.ax*dt
j.yvel+=0.5*j.ay*dt
computeAccelerations(j)
for j in list:
j.xvel+=0.5*j.ax*dt
j.yvel+=0.5*j.ay*dt
canvas.after(10) #duration of frame in ms
for z in list:
canvas.move(z.ball,z.xvel, z.yvel)
canvas.update()
window.mainloop() #keeps the window open