Created
October 13, 2021 08:33
-
-
Save DaelonSuzuka/d373da57bff24cfffaa558430a765853 to your computer and use it in GitHub Desktop.
Godot ObserverCam2D
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends Camera2D | |
# This script turns a Camera2D into a mouse-controllable ObserverCamera | |
# Holding the Middle Mouse button and moving the mouse pans the camera | |
# Mouse Scroll Wheel zooms the camera in and out | |
# Clicking the Middle Mouse button without moving the camera resets the camera | |
# Checking 'force_current' will continually set this camera as 'current'. | |
# This is necessary because Godot seems to set every camera to current when it | |
# enters the scene tree. | |
export var force_current := false | |
func _process(delta): | |
if force_current: | |
current = true | |
# save the original zoom and position so we can reset it later | |
onready var original_position := position | |
onready var original_zoom := zoom | |
func reset(): | |
zoom = original_zoom | |
position = original_position | |
# variables used to manage dragging | |
var mouse_start_pos: Vector2 | |
var screen_start_position: Vector2 | |
var dragging := false | |
func _input(event): | |
if !current: | |
return | |
if event is InputEventMouseButton: | |
match event.button_index: | |
BUTTON_MIDDLE: | |
if event.is_pressed(): | |
mouse_start_pos = event.position | |
screen_start_position = position | |
dragging = true | |
else: | |
dragging = false | |
if mouse_start_pos == event.position: | |
reset() | |
BUTTON_WHEEL_UP: | |
zoom.x -= .1 | |
zoom.y -= .1 | |
BUTTON_WHEEL_DOWN: | |
zoom.x += .1 | |
zoom.y += .1 | |
# do the actual dragging | |
elif event is InputEventMouseMotion and dragging: | |
position = zoom * (mouse_start_pos - event.position) + screen_start_position |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment