Coding camera to go to specific rotations depending on button pressed

Godot Version

4.4.1

Question

This might be a little confusing to explain but I’ll try my best. I am completely new to godot, and I’m making a small cooking game.

I want the camera to be in the middle of a room and be able to focus on different work stations with a button press. For example, the 1 key would go to the window, the 2 key would go to the grill, etc. How would I code the camera to do this? I want it to rotate to an exact position, and no tutorial I’ve looked at tells me how to do that.

Thanks!

The solution i’m posting does not use keys 1-9, but utilizes a next/previous system. If you want me to show you how to use the individual keys i can, but then you’d be limited to only 9 cameras, you could have a tenth if you wanted to use the 0 key. But the method i’m sharing has virtually limitless options for camera positions.

Here is my mock up scene tree, the only important things to make note of are the cameras having the unique name applied to them and the scrip at scene root.

Note: I’ve hidden the necessary scripting and scene nodes for ui as displayed in the video

extends Node3D
@onready var game_camera: Camera3D = %GameCamera
@onready var camera_array : Array = [%Camera1, %Camera2, %Camera3, %Camera4, %Camera5, %Camera6, %Camera7, %Camera8, %Camera9]

var cam_index : int = 0
var next_camera : Node3D

func _ready() -> void:
	set_camera()
	print(cam_index)

func _input(event: InputEvent) -> void:
	if event.is_action_pressed("next"):
		change_cam_next()
	if event.is_action_pressed("previous"):
		change_cam_previous()
		

func change_cam_next():
	if cam_index == camera_array.size() - 1:
		print("cannot go further")
	else:
		cam_index += 1
		set_camera()
		print(cam_index)

func change_cam_previous():
	if cam_index == 0:
		print("cannot go further")
	else:
		cam_index -= 1
		set_camera()
		print(cam_index)

func set_camera():
	next_camera = camera_array[cam_index]
	game_camera.transform = next_camera.transform

I would have shared a video of it working but i cannot.
Just put the camera position nodes where you want them, and at whatever rotation you want them to be and you’re good to go!

1 Like

My previous post works more like a security camera, in the set_camera function replace
game_camera.transform = next_camera.transform

with

game_camera.look_at(next_camera.position)

If you need more help with look at, you can check out the Godot documentation.

2 Likes