How do i switch to the nearest camera and switch back to a player camera?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ceayo

How do i switch to the nearest camera and switch back to a player camera?

I have a player with a firstperson camera, which i want to be able to switch to another camera, which should be the nearest camera from the player.

:bust_in_silhouette: Reply From: Pomelo

First of all, I am not sure if you are asking how to switch cameras in general. Assuming you know how to do that, and you are asking how to know which camera is the closest one, one way would be to add all the cameras to a group, lets say “cameras”, and then iterate looking for the closest one like this: (pseudo-code, since I dont recall exactly how certain methods are written):

var closest_distance = 0
var closest_camera
for camera in get_nodes_in_group("cameras"):
    var distance = self.position.distance_to(camera.position)
    if closest_distance == 0: 
        closest_distance = distance
        closest_camera = camera
    if distance < closest_distance:
        closest_distance = distance
        closest_camera = camera