shmodot/scripts/OrbitCamera.cs

81 lines
1.8 KiB
C#
Raw 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;
[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 20:40:39 +02:00
private void Zoom(float amount)
{
Camera.Fov += amount * _zoomSensitivity / Camera.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
}
}