Zoom to cursor for Camera2D script in Godot 4.2 :
extends Camera2D
var zoom_min = Vector2(1, 1)
var zoom_max = Vector2(2, 2)
var zoom_speed = Vector2(0.1, 0.1)
var screen_width = 1920
var screen_height = 1080
func _input(event):
if event is InputEventMouseButton:
if event.is_pressed():
if event.button_index == MOUSE_BUTTON_WHEEL_UP:
zoom_in()
if event.button_index == MOUSE_BUTTON_WHEEL_DOWN:
zoom_out()
func zoom_in():
if zoom < zoom_max:
var old_zoom = zoom
var new_zoom = old_zoom + zoom_speed
update_zoom(old_zoom, new_zoom)
func zoom_out():
if zoom > zoom_min:
var old_zoom = zoom
var new_zoom = old_zoom - zoom_speed
update_zoom(old_zoom, new_zoom)
func update_zoom(old_zoom: Vector2, new_zoom: Vector2):
var mouse_x = get_viewport().get_mouse_position().x
var mouse_y = get_viewport().get_mouse_position().y
var pixels_difference_x = (screen_width / old_zoom.x) - (screen_width / new_zoom.y)
var pixels_difference_y = (screen_height / old_zoom.y) - (screen_height / new_zoom.y)
var side_ratio_x = (mouse_x - (screen_width / 2)) / screen_width
var side_ratio_y = (mouse_y - (screen_height / 2)) / screen_height
position.x += pixels_difference_x * side_ratio_x
position.y += pixels_difference_y * side_ratio_y
zoom = new_zoom
if position != get_screen_center_position():
position = get_screen_center_position()