Switch Camera2D back

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

I have 3 Camera2D Nodes (A,B,C). A or B is current. Then I set C current. How can I switch back to the Camera2D, which was current before C.

:bust_in_silhouette: Reply From: njamster

There is no built-in way of doing that, you’ll have to code it yourself:

onready var current_camera = null
onready var previous_camera = null

func _ready():
for child in get_children():
	if child is Camera2D and child.current:
		current_camera = child

func _process(delta):
	if Input.is_action_just_pressed("ui_accept"):
		change_camera($C)

	if Input.is_action_just_pressed("ui_cancel"):
		revert_camera()

func change_camera(camera_node):
	previous_camera = current_camera
	current_camera = camera_node
	camera_node.current = true

func revert_camera():
	if previous_camera:
		change_camera(previous_camera)

You’d need to attach this code to a scene which has two Camera2D-children named “A” and “C”. “A” will be the default camera, pressing “ui_accept” (defaulting to the space key) will change the camera to “C”, pressing “ui_cancel” (defaulting to the escape key) will revert back to “A”. Note that this is not hard-coded, so if you’d create another child node “B” and make that the defaul, it would still work as expected.

If you want to go back further in time, you need to create an array keeping track of the camera history. I’ll just outline the parts of the script that would change:

onready var camera_history = []
    
func change_camera(camera_node, remember=true):
	if remember:
		camera_history.append(current_camera)
	current_camera = camera_node
	camera_node.current = true

func revert_camera():
	if not camera_history.empty():
		var previous_camera = camera_history.pop_back()
		change_camera(previous_camera, false)

I assume all cameras to be permanent available here. If you free any of them, this will stop working, as it directly stores the references to the camera nodes.

Thanks you very much!

Godot_Starter | 2020-02-24 16:59