VPython Physics Simulation Lagging After Running Pause Function

249 Views Asked by At

I'm making a physics simulation in VPython glowscript, and I need to be able to pause and play my program at the press of a button. So far, I've added the pause/play button, and it works great! However, after unpausing the simulation, Once I've paused it for the first time, It lags horribly. I'm not sure how to fix this to be honest. Could someone help?

Here's a link to my Vpython code, as well as my code I've added here.

GlowScript 3.0 VPython
scene.background = vector(0,0.7,1)
scene.width = 400



# Setting Inital Variables
degrees = 45
theta = -degrees*(pi/180)
omega = 0
L=1
alpha = -sin(theta)
t=0
tMax = 9999
dt = 0.01
damp = 0.5
driveAmp = 1.2
driveFreq = 2/3
running = True

def Run(b):
    global running, last_dt, dt
    running = not running
    if running:
        b.text = "Pause"
        dt = last_dt
    else:
        b.text = "Run"
        last_dt = dt
        dt = 0
    return
    
button(text="Pause", bind=Run)

support = box(pos=vector(0,0,0), size = vector(0.2, 0.01, 0.2)) 
ball = sphere(pos=vector(support.pos.x-L*sin(theta),support.pos.y-L*cos(theta),0), radius=0.05, color=color.green) 
string = cylinder(pos=support.pos, axis=ball.pos-support.pos, color=color.white, radius=0.008)

def torque(theta, omega, t):
    return -sin(theta) - damp*omega + driveAmp*sin(driveFreq*t)

    
# Create graph
Pendulum_graph = graph(width=600, height=375, 
        title="Theta vs Time",
        xtitle="<i>Time (s) </i>", ytitle="<i>Theta (radians) </i>",
        background=color.white)

# Set time variable, and the color of the graph dots
vyDots = gdots(color=color.green, interval=30)




while (True):
    rate(1/dt)
    
    alpha = torque(theta, omega, t)
    
    thetaMid = theta + omega*0.5*dt
    
    omegaMid = omega + alpha*0.5*dt
    
    dtmid = dt*0.5
    
    tmid = 0.5*t
    
    alphaMid = torque(thetaMid, omegaMid, tmid)
    
    theta += omegaMid * dt
    
    
    omega += alphaMid*dt
    
    vyDots.plot(t,theta)
    tmid+= dtmid
    
    t += dt
    
    x = sin(theta)
    y = -cos(theta)
    
    ball.pos = vector(x,y,0)
    string.axis = ball.pos
    
    
    

        

    
    
    
                                         # y = theta , vy = omega, alpha = ay
    

    # 12 -  10 seconds. What is the significance of this value?
    # 13 - The graph is all crazy for about 90 seconds, and then it eventually equals out into a perodic motion

    
    
2

There are 2 best solutions below

0
On

The problem is in this line:

rate(1/dt)

When you press button dt becomes equal to zero. Don't know how the GlowScript resolves this problem (ordinary Python issues ZeroDivisionError, when using this program in IDLE). So change it with usual

rate(100)

and it will be ok.

0
On

Also, in the loop, do all the calculations based on "if running:".