A good approach to repositioning a camera onto an enemy and back to the player

Godot Version

Godot_v4.5.1

Question

Hello all! I’m new to posting on the forum, so excuse me if my question isn’t entirely succinct. I’m wanting to change a Camera3D’s position to lock onto an enemy and return back to the player in a 3D space when disabling lock on, but I don’t quite understand where to start regarding how to reposition the camera. Would it make sense to adjust the existing camera to follow a point on a target, or detach the camera from the player and place it on the enemy, or something else?

Hi,

Ideally, your camera node should not be attached to the player node, both should be separate. That way, you can attach a script to your camera that follows a target, most of the time it will be the player, and then you can switch that target to any enemy.
Camera movement code by itself will do the smooth motion between the targets.

1 Like

I think you can do both. But I would prefer camera following a point.
You can create a camera script and it can have a variable called ‘target’. It would always follow the target, if there’s any, in the process function. You can change target to enemy or player.

extends Camera3D

var target

func _process(delta):
	if target:
		position = target.position

There may be different approaches also..

2 Likes

Following up on the @lastbender’s suggestion, you can also smooth the movement with a simple lerp.

extends Camera3D

const FOLLOW_SPEED: float = 5.0

var target: Node3D

func _process(delta: float) -> void:
	if target:
		global_position = global_position.lerp(target.global_position, FOLLOW_SPEED * delta)
2 Likes

Thank you!!