shmodot/scripts/OrbitCamera.cs

91 lines
2.1 KiB
C#
Raw Permalink Normal View History

2022-08-04 22:20:29 +02:00
using Godot;
using System;
public class OrbitCamera : Spatial
{
[Export]
2022-09-05 20:40:39 +02:00
private float _lookSensitivity = 200f;
[Export]
private float _zoomSensitivity = 10f;
2022-09-05 21:09:34 +02:00
[Export]
private Vector2 _fovRange = new Vector2(10, 60);
2022-09-05 20:40:39 +02:00
[Export]
private NodePath _cameraPath;
private Camera _camera = null;
private Camera Camera
{
get
{
if (_camera == null)
{
_camera = GetNode<Camera>(_cameraPath);
}
return _camera;
}
}
2022-08-04 22:20:29 +02:00
2022-09-04 18:37:35 +02:00
private Vector2 _rotation;
private bool _canRotate = false;
2022-08-04 22:20:29 +02:00
2022-09-04 18:37:35 +02:00
public override void _Input(InputEvent e)
{
if (e is InputEventMouseMotion mouseMotion)
{
HandleMouseMovement(mouseMotion);
}
if (e is InputEventMouseButton mouseButton)
{
HandleMouseButton(mouseButton);
}
2022-08-04 22:20:29 +02:00
}
public override void _Process(float delta)
{
2022-09-04 18:37:35 +02:00
Rotation = Vector3.Zero;
2022-09-05 20:40:39 +02:00
var sensitivity = -1f / _lookSensitivity;
2022-09-04 18:37:35 +02:00
Rotate(Vector3.Right, _rotation.y * sensitivity);
Rotate(Vector3.Up, _rotation.x * sensitivity);
}
// left click to drag
private void HandleMouseButton(InputEventMouseButton mouseButton)
{
2022-09-05 20:40:39 +02:00
switch ((ButtonList)mouseButton.ButtonIndex)
{
case ButtonList.Left:
_canRotate = mouseButton.Pressed;
break;
case ButtonList.WheelUp:
Zoom(-1);
break;
case ButtonList.WheelDown:
Zoom(1);
break;
}
}
2022-09-04 18:37:35 +02:00
2022-09-05 21:09:34 +02:00
private void Zoom(int dir)
2022-09-05 20:40:39 +02:00
{
2022-09-05 21:09:34 +02:00
if (dir != 1 && dir != -1)
throw new ArgumentException();
var fov = Camera.Fov;
var zoom = _zoomSensitivity / Camera.Fov;
fov += (float)dir * zoom;
fov = Mathf.Clamp(fov, _fovRange.x, _fovRange.y);
Camera.Fov = fov;
2022-09-04 18:37:35 +02:00
}
private void HandleMouseMovement(InputEventMouseMotion mouseMotion)
{
if (!_canRotate) return;
var delta = mouseMotion.Relative;
_rotation += delta;
2022-08-04 22:20:29 +02:00
}
}