follow_camera.gd 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. extends Camera3D
  2. var collision_exception = []
  3. @export var min_distance = 0.5
  4. @export var max_distance = 3.0
  5. @export var angle_v_adjust = 0.0
  6. var max_height = 2.0
  7. var min_height = 0
  8. @onready var target_node: Node3D = get_parent()
  9. func _ready():
  10. collision_exception.append(target_node.get_parent().get_rid())
  11. # Detaches the camera transform from the parent spatial node
  12. set_as_top_level(true)
  13. func _physics_process(_delta):
  14. var target_pos: Vector3 = target_node.global_transform.origin
  15. var camera_pos: Vector3 = global_transform.origin
  16. var delta_pos: Vector3 = camera_pos - target_pos
  17. # Regular delta follow
  18. # Check ranges
  19. if delta_pos.length() < min_distance:
  20. delta_pos = delta_pos.normalized() * min_distance
  21. elif delta_pos.length() > max_distance:
  22. delta_pos = delta_pos.normalized() * max_distance
  23. # Check upper and lower height
  24. delta_pos.y = clamp(delta_pos.y, min_height, max_height)
  25. camera_pos = target_pos + delta_pos
  26. look_at_from_position(camera_pos, target_pos, Vector3.UP)
  27. # Turn a little up or down
  28. var t = transform
  29. t.basis = Basis(t.basis[0], deg_to_rad(angle_v_adjust)) * t.basis
  30. transform = t