main.lua 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. -- Newton's cradle: array of balls suspended from two strings, demonstrating conservation of energy / momentum
  2. -- Strings are modeled with distance joints, which means they behave more like rods.
  3. local world
  4. local frame
  5. local framePose
  6. local balls = {}
  7. local count = 10
  8. local radius = 1 / count / 2
  9. -- small air gap between balls results in collisions in separate frames, to carry impulse through to last ball
  10. -- without this gap the physics engine would need to calculate transfer of impulses between contacts
  11. local gap = 0.01
  12. function lovr.load()
  13. world = lovr.physics.newWorld(0, -9.8, 0, false)
  14. -- a static geometry from which balls are suspended
  15. local size = vec3(1.2, 0.1, 0.3)
  16. frame = world:newBoxCollider(vec3(0, 2, -1), size)
  17. frame:setKinematic(true)
  18. framePose = lovr.math.newMat4(frame:getPose()):scale(size)
  19. -- create balls along the length of frame and attach them with two distance joints to frame
  20. for x = -0.5, 0.5, 1 / count do
  21. local ball = world:newSphereCollider(vec3(x, 1, -1), radius - gap)
  22. ball:setRestitution(1)
  23. lovr.physics.newDistanceJoint(frame, ball, vec3(x, 2, -1 + 0.25), vec3(x, 1, -1))
  24. lovr.physics.newDistanceJoint(frame, ball, vec3(x, 2, -1 - 0.25), vec3(x, 1, -1))
  25. table.insert(balls, ball)
  26. end
  27. -- displace the last ball to set the Newton's cradle in motion
  28. local lastBall = balls[#balls]
  29. lastBall:setPosition(vec3(lastBall:getPosition()) + vec3(5 * radius, 5 * radius, 0))
  30. lovr.graphics.setBackgroundColor(0.1, 0.1, 0.1)
  31. end
  32. function lovr.draw()
  33. lovr.graphics.setColor(0, 0, 0)
  34. lovr.graphics.box('fill', framePose)
  35. lovr.graphics.setColor(1, 1, 1)
  36. for i, ball in ipairs(balls) do
  37. local position = vec3(ball:getPosition())
  38. lovr.graphics.sphere(position, radius)
  39. end
  40. end
  41. function lovr.update(dt)
  42. world:update(1 / 72)
  43. end