pendulum.script 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. local function draw_line(from, to)
  2. msg.post("@render:", "draw_line", { start_point = from, end_point = to, color = vmath.vector4(1,0,0,1) }) -- <1>
  3. end
  4. function init(self)
  5. msg.post(".", "acquire_input_focus") -- <2>
  6. self.gravity = physics.get_gravity() -- <3>
  7. self.pivot_pos = go.get_position() -- <4>
  8. local center_anchor = vmath.vector3(0, 0, 0) -- <5>
  9. local pivot = "pivot#collisionobject"
  10. local weight_fixed = "weight_fixed#collisionobject"
  11. local weight_spring = "weight_spring#collisionobject"
  12. physics.create_joint(physics.JOINT_TYPE_FIXED, weight_fixed, "weight_fixed_joint", center_anchor, pivot, center_anchor, {max_length = 250}) -- <6>
  13. physics.create_joint(physics.JOINT_TYPE_SPRING, weight_spring, "weight_spring_joint", center_anchor, pivot, center_anchor, {length = 150, frequency = 1, damping = 0}) -- <7>
  14. end
  15. function update(self, dt)
  16. local weight_pos = go.get_position("/weight_fixed") -- <8>
  17. local weight1_pos = go.get_position("/weight_spring")
  18. draw_line(self.pivot_pos, weight_pos) -- <9>
  19. draw_line(self.pivot_pos, weight1_pos)
  20. end
  21. function on_input(self, action_id, action)
  22. if action_id == hash("touch") and action.pressed then -- <10>
  23. if self.gravity.y ~= 0 then -- <11>
  24. self.gravity.y = 0
  25. self.gravity.x = 500
  26. else
  27. self.gravity.y = -500
  28. self.gravity.x = 0
  29. end
  30. physics.set_gravity(self.gravity) -- <12>
  31. end
  32. end
  33. --[[
  34. 1. Helper function to draw a line between two points.
  35. 2. Tell the engine that this object ("." is shorthand for the current game object) should listen to input. Any input will be received in the `on_input()` function.
  36. 3. Get current physics gravity vector and store it in self reference to change it later.
  37. 4. Get current position of the pivot and store it in self reference for drawing a line between the pivot and weights.
  38. 5. Store vector used for anchoring joints and collision objects ids in local variables for ease of use in below function.
  39. 6. Create a fixed joint between a first weight and the pivot
  40. 7. create a spring type joing between the second weight and the pivot.
  41. 8. Get updated positions of both weights.
  42. 9. Draw lines between the weights and the pivot.
  43. 10. If we receive input (touch or mouse click) we switch the direction of the gravity pull.
  44. 11. If the gravity is set to the bottom of the screen, set it so it pulls to the right, in other case, set it back to pull to the bottom.
  45. 12. Set the new gravity vector.
  46. --]]