Godot Version
4.3
Question
I’m making a tower defence game with a camera that I can move with middle mouse click and zoom. When I zoom in, I want to camera to center my mouse position. I wrote this camera code:
extends Camera2D
var target_zoom : Vector2
var zoom_speed : float = 10.0
var zooming : bool = false
var mouse_pos : Vector2
func _unhandled_input(event: InputEvent) -> void:
if event is InputEventMouseMotion:
if event.button_mask == MOUSE_BUTTON_MASK_MIDDLE:
Input.set_default_cursor_shape(Input.CURSOR_POINTING_HAND)
zooming = false
position -= event.relative / zoom
else:
Input.set_default_cursor_shape(Input.CURSOR_ARROW)
func _process(delta: float) -> void:
zoom = clamp(zoom, Vector2(0.2, 0.2), Vector2(3, 3))
if zooming:
zoom = lerp(zoom, target_zoom, zoom_speed * delta)
if target_zoom > zoom:
position = lerp(position, mouse_pos, 5.0 * delta)
if Input.is_action_just_released("scroll_up"):
zooming = true
target_zoom = zoom - Vector2(0.2, 0.2)
mouse_pos = get_global_mouse_position()
if Input.is_action_just_released("scroll_down"):
zooming = true
target_zoom = zoom + Vector2(0.2, 0.2)
mouse_pos = get_global_mouse_position()
But what happens is, I zoom to mouse position, mouse stands still on it’s place and when I zoom again, it changes it’s position to the mouse direction again. I want to center the mouse so when I zoom again camera will stand at same position. Can somebody help me with that? Thanks from now!