camera.gd 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. extends Camera3D
  2. const MOUSE_SENSITIVITY = 0.002
  3. const MOVE_SPEED = 1.5
  4. var rot = Vector3()
  5. var velocity = Vector3()
  6. func _ready():
  7. Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
  8. func _input(event):
  9. # Mouse look (only if the mouse is captured).
  10. if event is InputEventMouseMotion and Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
  11. # Horizontal mouse look.
  12. rot.y -= event.relative.x * MOUSE_SENSITIVITY
  13. # Vertical mouse look.
  14. rot.x = clamp(rot.x - event.relative.y * MOUSE_SENSITIVITY, -1.57, 1.57)
  15. transform.basis = Basis.from_euler(rot)
  16. if event.is_action_pressed("toggle_mouse_capture"):
  17. if Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
  18. Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)
  19. else:
  20. Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
  21. func _process(delta):
  22. var motion = Vector3(
  23. Input.get_axis(&"move_left", &"move_right"),
  24. 0,
  25. Input.get_axis(&"move_forward", &"move_back")
  26. )
  27. # Normalize motion to prevent diagonal movement from being
  28. # `sqrt(2)` times faster than straight movement.
  29. motion = motion.normalized()
  30. velocity += MOVE_SPEED * delta * (transform.basis * motion)
  31. velocity *= 0.85
  32. position += velocity