Godot Version
v4.2.2.stable.official [15073afe3]
Question
I have found some code on reddit for camera panning because I was struggling with the camera’s pan speed.
The code below has both my version and the reddit post’s version, selectable with the variant1 variable.
Please enlighten me why (my) variant1 does not work the same as variant2.
The only notable difference seems to be that I am using a Tween instead of directly manipulating the global_position of the Camera2D.
extends Camera2D
const ZOOM_INCREMENT = 0.05
const ZOOM_MIN = 0.5
const ZOOM_MAX = 5.0
var panning := false
var zoom_level := 1.0
var variant1 = true
func _unhandled_input(_event:InputEvent) -> void:
if _event is InputEventMouseButton:
match _event.button_index:
MOUSE_BUTTON_LEFT:
if Input.is_key_pressed(KEY_CTRL):
if _event.pressed:
panning = true
else:
panning = false
get_tree().get_root().set_input_as_handled()
MOUSE_BUTTON_WHEEL_UP:
zoom_level = clamp(zoom_level + ZOOM_INCREMENT, ZOOM_MIN, ZOOM_MAX)
zoom = zoom_level * Vector2.ONE
get_tree().get_root().set_input_as_handled()
MOUSE_BUTTON_WHEEL_DOWN:
zoom_level = clamp(zoom_level - ZOOM_INCREMENT, ZOOM_MIN, ZOOM_MAX)
zoom = zoom_level * Vector2.ONE
get_tree().get_root().set_input_as_handled()
elif _event is InputEventMouseMotion and panning:
get_tree().get_root().set_input_as_handled()
if Input.is_mouse_button_pressed(MOUSE_BUTTON_LEFT) and Input.is_key_pressed(KEY_CTRL):
if variant1:
var tween = get_tree().create_tween()
tween.tween_property(
self,
"global_position",
self.global_position - (_event.relative / zoom_level),
0.2
#Input.get_last_mouse_velocity().length()
).set_trans(Tween.TRANS_LINEAR).set_ease(Tween.EASE_IN_OUT)
else:
global_position -= _event.relative / zoom_level
else:
panning = false