aspring1.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. """Simulation of a block connected to a spring in a viscous medium"""
  2. from vedo import *
  3. L = 0.1 # spring x position at rest
  4. x0 = 0.85 # initial x-coordinate of the block
  5. k = 25 # spring constant
  6. m = 20 # block mass
  7. b = 0.5 # viscosity friction (proportional to velocity)
  8. dt = 0.15 # time step
  9. v = vector(0, 0, 0.2) # initial conditions
  10. x = vector(x0, 0, 0)
  11. x0 = vector(-0.8, 0, 0)
  12. xr = vector(L, 0, 0)
  13. def loop_func(event):
  14. global v, x
  15. F = -k * (x - xr) - b * v # force and friction
  16. a = F / m # acceleration
  17. v = v + a*dt # velocity
  18. x = x + v*dt + 1/2 * a * dt**2 # position
  19. block.pos(x) # update block position and trail
  20. spr = Spring(x0, x, r1=0.06, thickness=0.01)
  21. plt.remove("Spring").add(spr).render()
  22. block = Cube(pos=x, side=0.2).color("tomato")
  23. spring = Spring(x0, x, r1=0.06, thickness=0.01)
  24. plt = Plotter(size=(1050, 600))
  25. plt += Box(pos=(0, -0.1, 0), size=(2.0, 0.02, 0.5)) # floor
  26. plt += Box(pos=(-0.82, 0.15, 0), size=(0.04,0.50,0.3)) # wall
  27. plt += [block, spring, __doc__]
  28. plt.add_callback("timer", loop_func)
  29. plt.timer_callback("start")
  30. plt.show().close()