aspring2_player.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. """Animation of a block attached to a spring"""
  2. from vedo import *
  3. from vedo.applications import AnimationPlayer
  4. L = 0.1 # spring x position at rest
  5. x0 = 0.85 # initial x-coordinate of the block
  6. k = 20 # spring constant
  7. m = 20 # block mass
  8. b = 5 # viscosity friction (proportional to velocity)
  9. dt = 0.15 # time step
  10. v = vector(0, 0, 0.3) # initial conditions
  11. x = vector(x0, 0, 0)
  12. xr = vector(L, 0, 0)
  13. x0 = vector(-0.8, 0, 0)
  14. # Pre-compute the trajectory of the block and store it in a list.
  15. history_x = []
  16. for i in range(200):
  17. F = -k * (x - xr) - b * v # force and friction
  18. a = F / m # acceleration
  19. v = v + a * dt # velocity
  20. x = x + v * dt + 1/2 * a * dt**2 # position
  21. history_x.append(x)
  22. # Create the objects to be shown in the animation
  23. floor = Box(pos=(0, -0.1, 0), size=(2.0, 0.02, 0.5)).c('yellow2')
  24. wall = Box(pos=(-0.82, 0.15, 0), size=(0.04, 0.50, 0.3)).c('yellow2')
  25. block = Cube(pos=x, side=0.2).c("tomato")
  26. spring= Spring(x0, x, r1=0.05, thickness=0.005)
  27. text = Text2D(font="Calco", c='white', bg='k', alpha=1, pos='top-right')
  28. # Create the animation player and it's callback function
  29. def update_scene(i: int):
  30. # update block and spring position at frame i
  31. block.pos(history_x[i])
  32. spring = Spring(x0, history_x[i], r1=0.05, thickness=0.005)
  33. text.text(f"Frame number {i}\nx = {history_x[i][0]:.4f}")
  34. plt.remove("Spring").add(spring).render()
  35. plt = AnimationPlayer(update_scene, irange=[0,200], loop=True)
  36. plt += [floor, wall, block, spring, text, __doc__]
  37. plt.set_frame(0)
  38. plt.show()
  39. plt.close()