main.lua 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. -- Physics construct of saloon doors using the motorized hinge joint
  2. local world
  3. local doorR, doorL
  4. local passenger
  5. function lovr.load()
  6. world = lovr.physics.newWorld(0, -9.8, 0, false)
  7. -- a static geometry that functions as door frame
  8. doorR = world:newBoxCollider(vec3( 0.55, 0.5, -1), vec3(1, 1, 0.2))
  9. doorL = world:newBoxCollider(vec3(-0.55, 0.5, -1), vec3(1, 1, 0.2))
  10. -- attach doors with vertical hinges
  11. local hingeR = lovr.physics.newHingeJoint(nil, doorR, vec3( 1, 0, -1), vec3(0,1,0))
  12. local hingeL = lovr.physics.newHingeJoint(nil, doorL, vec3(-1, 0, -1), vec3(0,1,0))
  13. -- set up motors to return the doors to their initial orientation
  14. hingeR:setMotorMode('position')
  15. hingeL:setMotorMode('position')
  16. hingeR:setMotorTarget(0)
  17. hingeL:setMotorTarget(0)
  18. -- a controlled capsule that moves in and out pushing the door both ways
  19. passenger = world:newCapsuleCollider(0, 0, 0, 0.4, 1)
  20. passenger:getShape():setOffset(0, 0.5, 0, math.pi/2, 1, 0, 0)
  21. passenger:setKinematic(true)
  22. passenger:moveKinematic(vec3(0, 0, -4), nil, 3)
  23. end
  24. function lovr.draw(pass)
  25. for i, collider in ipairs(world:getColliders()) do
  26. pass:setColor(i / 3, i / 3, i / 3)
  27. local shape = collider:getShape()
  28. local pose = mat4(collider:getPose()) * mat4(shape:getOffset())
  29. local shape_type = shape:getType()
  30. if shape_type == 'box' then
  31. local size = vec3(collider:getShape():getDimensions())
  32. pass:box(pose:scale(size))
  33. elseif shape_type == 'capsule' then
  34. local l, r = shape:getLength(), shape:getRadius()
  35. pose:scale(r, r, l)
  36. pass:capsule(pose, segments)
  37. end
  38. end
  39. end
  40. function lovr.update(dt)
  41. local t = lovr.timer.getTime()
  42. -- every 3 seconds change the moving direction of capsule collider
  43. if t % 3 < dt then
  44. local _, _, z = passenger:getPosition()
  45. z = z > -1 and -4 or 2
  46. -- moveKinematic is prefered over setPosition as it will correctly set the passenger's velocity
  47. passenger:moveKinematic(vec3(0, 0, z), nil, 3)
  48. end
  49. world:update(dt)
  50. end