2
0

camera.lua 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. require "lua/class"
  2. local wkey = false
  3. local skey = false
  4. local akey = false
  5. local dkey = false
  6. FPSCamera = class(FPSCamera)
  7. function FPSCamera:init(world, unit)
  8. self._world = world
  9. self._unit = unit
  10. self._sg = World.scene_graph(world)
  11. self._translation_speed = 0.05
  12. self._rotation_speed = 0.006
  13. end
  14. function FPSCamera:unit()
  15. return self._unit;
  16. end
  17. function FPSCamera:camera()
  18. return World.camera(self._world, self._unit)
  19. end
  20. function FPSCamera:update(dx, dy)
  21. if Keyboard.pressed(Keyboard.button_id("w")) then wkey = true end
  22. if Keyboard.pressed(Keyboard.button_id("s")) then skey = true end
  23. if Keyboard.pressed(Keyboard.button_id("a")) then akey = true end
  24. if Keyboard.pressed(Keyboard.button_id("d")) then dkey = true end
  25. if Keyboard.released(Keyboard.button_id("w")) then wkey = false end
  26. if Keyboard.released(Keyboard.button_id("s")) then skey = false end
  27. if Keyboard.released(Keyboard.button_id("a")) then akey = false end
  28. if Keyboard.released(Keyboard.button_id("d")) then dkey = false end
  29. local camera = self:camera()
  30. local camera_transform = SceneGraph.instances(self._sg, self._unit)
  31. local camera_local_pose = SceneGraph.local_pose(self._sg, camera_transform)
  32. local camera_right_vector = Matrix4x4.x(camera_local_pose)
  33. local camera_position = Matrix4x4.translation(camera_local_pose)
  34. local camera_rotation = Matrix4x4.rotation(camera_local_pose)
  35. local view_dir = Matrix4x4.z(camera_local_pose)
  36. -- Rotation
  37. local rotation_around_world_up = Quaternion(Vector3(0, 1, 0), -dx * self._rotation_speed)
  38. local rotation_around_camera_right = Quaternion(camera_right_vector, -dy * self._rotation_speed)
  39. local rotation = Quaternion.multiply(rotation_around_world_up, rotation_around_camera_right)
  40. local old_rotation = Matrix4x4.from_quaternion(camera_rotation)
  41. local delta_rotation = Matrix4x4.from_quaternion(rotation)
  42. local new_rotation = Matrix4x4.multiply(old_rotation, delta_rotation)
  43. Matrix4x4.set_translation(new_rotation, camera_position)
  44. -- Fixme
  45. SceneGraph.set_local_pose(self._sg, camera_transform, new_rotation)
  46. -- Translation
  47. if wkey then camera_position = camera_position + view_dir end
  48. if skey then camera_position = camera_position + view_dir * -1 end
  49. if akey then camera_position = camera_position + camera_right_vector * -1 end
  50. if dkey then camera_position = camera_position + camera_right_vector end
  51. SceneGraph.set_local_position(self._sg, camera_transform, camera_position)
  52. end