voxelgame/project/common/mouse_look.gd

73 lines
1.8 KiB
GDScript3
Raw Permalink Normal View History

extends Spatial
export var sensitivity = 0.4
export var min_angle = -90
export var max_angle = 90
export var capture_mouse = true
2017-08-27 15:54:21 +02:00
export var distance = 5.0
var _yaw = 0
var _pitch = 0
2017-08-27 15:54:21 +02:00
var _offset = Vector3()
func _ready():
2017-08-27 15:54:21 +02:00
_offset = get_translation()
if capture_mouse:
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
func _unhandled_input(event):
2017-08-13 00:28:44 +02:00
if event is InputEventMouseButton:
if event.pressed and Input.get_mouse_mode() != Input.MOUSE_MODE_CAPTURED:
if capture_mouse:
# Capture the mouse
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
2017-08-27 15:54:21 +02:00
if event.button_index == BUTTON_WHEEL_UP:
2019-06-01 20:03:42 +01:00
distance = max(distance - 1 - distance * 0.1, 0)
2017-08-27 15:54:21 +02:00
update_rotations()
elif event.button_index == BUTTON_WHEEL_DOWN:
2019-06-01 20:03:42 +01:00
distance = max(distance + 1 + distance * 0.1, 0)
2017-08-27 15:54:21 +02:00
update_rotations()
2017-08-13 00:28:44 +02:00
elif event is InputEventMouseMotion:
if Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED || not capture_mouse:
# Get mouse delta
2017-08-13 00:28:44 +02:00
var motion = event.relative
# Add to rotations
_yaw -= motion.x * sensitivity
_pitch += motion.y * sensitivity
# Clamp pitch
var e = 0.001
if _pitch > max_angle-e:
_pitch = max_angle-e
elif _pitch < min_angle+e:
_pitch = min_angle+e
# Apply rotations
2017-08-27 15:54:21 +02:00
update_rotations()
2017-08-13 00:28:44 +02:00
elif event is InputEventKey:
if event.pressed:
if event.scancode == KEY_ESCAPE:
# Get the mouse back
Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)
elif event.scancode == KEY_I:
var pos = get_translation()
2018-09-20 20:44:32 +01:00
var fw = -transform.basis.z
print("Position: ", pos, ", Forward: ", fw)
2017-08-27 15:54:21 +02:00
func update_rotations():
set_translation(Vector3())
set_rotation(Vector3(0, deg2rad(_yaw), 0))
rotate(get_transform().basis.x.normalized(), -deg2rad(_pitch))
set_translation(get_transform().basis.z * distance + _offset)