follow_camera.gd 1.2 KB

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