78 lines
2.6 KiB
GDScript
78 lines
2.6 KiB
GDScript
extends Camera2D
|
|
|
|
var last_mouse_position = Vector2.ZERO
|
|
|
|
var touch_start_positions = {}
|
|
var last_zoom_distance = -1
|
|
var last_zoom_center = Vector2.ZERO
|
|
|
|
func _ready():
|
|
set_process_input(true)
|
|
|
|
func _input(event):
|
|
print(event.as_text())
|
|
|
|
handle_mouse_events(event)
|
|
handle_touch_events(event)
|
|
|
|
func handle_mouse_events(event):
|
|
if event is InputEventMouseButton:
|
|
if event.button_index == MOUSE_BUTTON_RIGHT and event.pressed:
|
|
last_mouse_position = get_global_mouse_position()
|
|
elif event.button_index == MOUSE_BUTTON_RIGHT and not event.pressed:
|
|
last_mouse_position = Vector2.ZERO
|
|
elif 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()
|
|
|
|
# Macbook touchpad
|
|
elif event is InputEventPanGesture:
|
|
position+=event.delta
|
|
elif event is InputEventMagnifyGesture:
|
|
zoom_towards_mouse(Vector2(event.factor,event.factor))
|
|
|
|
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()
|
|
position += diff
|
|
|
|
func handle_touch_events(event):
|
|
if event is InputEventScreenTouch:
|
|
if event.pressed:
|
|
touch_start_positions[event.index] = event.position
|
|
if event.index==0:
|
|
$"../Touch1Sprite".position=event.position
|
|
if event.index==1:
|
|
$"../Touch2Sprite".position=event.position
|
|
if len(touch_start_positions) == 2:
|
|
last_zoom_distance = touch_start_positions[0].distance_to(touch_start_positions[1])
|
|
last_zoom_center = (touch_start_positions[0] + touch_start_positions[1]) / 2.0
|
|
else:
|
|
touch_start_positions.erase(event.index)
|
|
last_zoom_distance = -1
|
|
last_zoom_center = Vector2.ZERO
|
|
|
|
elif event is InputEventScreenDrag:
|
|
if event.index in touch_start_positions:
|
|
touch_start_positions[event.index] = event.position
|
|
if len(touch_start_positions) == 2:
|
|
var new_zoom_center = (touch_start_positions[0] + touch_start_positions[1]) / 2.0
|
|
var new_zoom_distance = touch_start_positions[0].distance_to(touch_start_positions[1])
|
|
|
|
if last_zoom_distance > 0:
|
|
var zoom_factor = last_zoom_distance / new_zoom_distance
|
|
zoom/=zoom_factor
|
|
position -= (new_zoom_center - last_zoom_center) / zoom
|
|
|
|
last_zoom_distance = new_zoom_distance
|
|
last_zoom_center = new_zoom_center
|