Godot version: 4.4.1
Hello. Thank you for making these forums available. I’m starting out making a side-scrolling open-world platformer. I was able to make the camera follow the player using a script (I heard it was better to do this in case you wanted the camera to do other things other than follow the player).
I followed a tutorial that made the player the target of the camera in the inspector panel.
However, I also want the player of my game to be able to zoom in on my player. Thus far I’ve been having great difficulty with this.
I’ve figured out how to make the camera zoom–I have it set so that the I key zooms in, O zooms out and P resets to the default zoom. I thought that setting the camera to follow the player would cause my zoom function to zoom to the center of the player node, but to my surprise it still zooms to the center of the viewport but at the position of the player.
Here is my present gd script.
extends Camera2D
@export var target: Node2D
# This script is a combination zoom function and follow player function.
# The values below are related to the zoom function.
const MIN_ZOOM = Vector2(1.0, 1.0)
const MAX_ZOOM = Vector2(2.0, 2.0)
const DEFAULT_ZOOM = Vector2(1.2, 1.2)
const ZOOM_SPEED = 1.0 # How fast it zooms per second
const RESET_SPEED = 5.0 # How fast it resets to default
var resetting_zoom := false
func _process(delta: float) -> void:
# --- Camera Follows Player: Player is set to target in inspector panel. ---
if target:
position = target.position
# --- Zoom Handling ---
var zoom_direction = 0.0
if Input.is_action_pressed("zoom_in"):
zoom_direction += 1.0
if Input.is_action_pressed("zoom_out"):
zoom_direction -= 1.0
if zoom_direction != 0.0:
resetting_zoom = false
var target_zoom = zoom + Vector2(zoom_direction, zoom_direction) * ZOOM_SPEED * delta
zoom = target_zoom.clamp(MIN_ZOOM, MAX_ZOOM)
elif resetting_zoom:
zoom = zoom.move_toward(DEFAULT_ZOOM, RESET_SPEED * delta)
if zoom == DEFAULT_ZOOM:
resetting_zoom = false
if Input.is_action_just_pressed("zoom_reset"):
resetting_zoom = true
I’m a novice programmer, getting help from LLMs to my dishonor. And even they can’t figure out how to make the camera zoom to the center of the player character.
One thing I don't want to do is make the Camera2D node a child of the player because of freedom. I prefer to have control of the camera. I actually did try the Camera2D approach and my zoom function still zoomed into the center of the screen.
I have a hard time believing that programs such as Glassbrick can make windows zoom in on your mouse pointer, yet Godot cannot zoom in on a location other than the center of the canvas.
If anyone can help I would appreciate it greatly, as this is one of the central functions I want to include in my game.