From 033a1c21da629ef4f3f948723aa6c465b0243fa7 Mon Sep 17 00:00:00 2001 From: James Date: Mon, 4 Dec 2023 18:04:59 +0000 Subject: [PATCH] finish zoom/scroll --- Camera2D.gd | 53 +++++++++++++++++++++++------------------------------ 1 file changed, 23 insertions(+), 30 deletions(-) diff --git a/Camera2D.gd b/Camera2D.gd index 65d39ff..7d6b174 100644 --- a/Camera2D.gd +++ b/Camera2D.gd @@ -1,37 +1,30 @@ extends Camera2D -var zoom_speed=Vector2(.2,.2) -var scrolling=false; +var last_mouse_position = Vector2.ZERO -# Called when the node enters the scene tree for the first time. func _ready(): - pass # Replace with function body. + set_process_input(true) func _input(event): if event is InputEventMouseButton: - if event.is_pressed(): - if event.button_index==MOUSE_BUTTON_WHEEL_UP: - zoom+=zoom_speed - if event.button_index==MOUSE_BUTTON_WHEEL_DOWN: - zoom-=zoom_speed - if event.button_index==MOUSE_BUTTON_MIDDLE: - scrolling=true - if event.is_released(): - if event.button_index==MOUSE_BUTTON_MIDDLE: - scrolling=false - if event is InputEventMouseMotion: - if scrolling: - offset-=event.velocity*0.1 - -# Called every frame. 'delta' is the elapsed time since the previous frame. -func _process(delta): - if Input.is_action_pressed('move_up'): - offset.y -= 1 - if Input.is_action_pressed('move_down'): - offset.y += 1 - if Input.is_action_pressed('move_left'): - offset.x -= 1 - if Input.is_action_pressed('move_right'): - offset.x += 1 -# if Input.is_action_just_pressed('take'): -# drop() + if event.button_index == MOUSE_BUTTON_MIDDLE and event.pressed: + last_mouse_position = get_global_mouse_position() + elif event.button_index == MOUSE_BUTTON_MIDDLE and not event.pressed: + last_mouse_position = Vector2.ZERO + if event.button_index == MOUSE_BUTTON_WHEEL_DOWN and event.pressed: + zoom_towards_mouse(Vector2(0.9, 0.9)) + elif event.button_index == MOUSE_BUTTON_WHEEL_UP and event.pressed: + zoom_towards_mouse(Vector2(1.1, 1.1)) + + elif event is InputEventMouseMotion: + if last_mouse_position != Vector2.ZERO: + var mouse_motion = event.relative + var drag_offset = mouse_motion / zoom + position -= drag_offset + last_mouse_position = get_global_mouse_position() + +func zoom_towards_mouse(zoom_factor): + var previous_mouse_position := get_local_mouse_position() + zoom *= zoom_factor + var diff = previous_mouse_position - get_local_mouse_position() + offset += diff