orbit_camera.script 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. -- The initial zoom level
  2. go.property("zoom", 3)
  3. -- The speed of the zoom
  4. go.property("zoom_speed", 0.1)
  5. -- The speed of the rotation
  6. go.property("rotation_speed", 0.5)
  7. -- The offset of the camera from the origin
  8. go.property("offset", vmath.vector3(0, 0, 0))
  9. function init(self)
  10. -- Acquire input focus to receive input events
  11. msg.post(".", "acquire_input_focus")
  12. -- Initialize start values
  13. self.yaw = go.get(".", "euler.y")
  14. self.pitch = go.get(".", "euler.x")
  15. self.zoom_offset = 0
  16. self.current_yaw = self.yaw
  17. self.current_pitch = self.pitch
  18. self.current_zoom = self.zoom_offset
  19. end
  20. function update(self, dt)
  21. -- Animate camera rotation and zoom
  22. self.current_yaw = vmath.lerp(0.15, self.current_yaw, self.yaw)
  23. self.current_pitch = vmath.lerp(0.15, self.current_pitch, self.pitch)
  24. self.current_zoom = vmath.lerp(0.15, self.current_zoom, self.zoom_offset)
  25. -- Calculate rotation and position
  26. local camera_yaw = vmath.quat_rotation_y(math.rad(self.current_yaw))
  27. local camera_pitch = vmath.quat_rotation_x(math.rad(self.current_pitch))
  28. local camera_rotation = camera_yaw * camera_pitch
  29. local camera_position = self.offset + vmath.rotate(camera_rotation, vmath.vector3(0, 0, self.zoom + self.current_zoom))
  30. -- Set camera position and rotation
  31. go.set_position(camera_position)
  32. go.set_rotation(camera_rotation)
  33. end
  34. function on_input(self, action_id, action)
  35. if action_id == hash("touch") and not action.pressed then
  36. self.yaw = self.yaw - action.dx * self.rotation_speed
  37. self.pitch = self.pitch + action.dy * self.rotation_speed
  38. elseif action_id == hash("mouse_wheel_up") then
  39. self.zoom_offset = self.zoom_offset - self.zoom * self.zoom_speed
  40. elseif action_id == hash("mouse_wheel_down") then
  41. self.zoom_offset = self.zoom_offset + self.zoom * self.zoom_speed
  42. end
  43. end