Created
November 4, 2023 00:56
-
-
Save valkyrienyanko/ac8a7e6b4b01a3e106f2e7bf173f5a63 to your computer and use it in GitHub Desktop.
This file contains 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
namespace SpaceGame; | |
public partial class CameraController : Node | |
{ | |
public event Action ZoomChanged; | |
[ExportGroup("Zoom")] | |
[Export(PropertyHint.Range, "0.02, 0.16")] | |
float zoomIncrementDefault = 0.02f; | |
[Export(PropertyHint.Range, "0.01, 10")] | |
float minZoom = 0.01f; | |
[Export(PropertyHint.Range, "0.1, 10")] | |
public float MaxZoom = 4.0f; | |
[Export(PropertyHint.Range, "0.01, 1")] | |
float smoothFactor = 0.25f; | |
float zoomIncrement = 0.02f; | |
float targetZoom; | |
Vector2 prevZoom; | |
Camera2D camera; | |
public override void _Ready() | |
{ | |
camera = GetParent<Camera2D>(); | |
// Make sure the camera zoom does not go past MinZoom | |
// Note that a higher MinZoom value means the camera can zoom out more | |
float maxZoom = Mathf.Max(camera.Zoom.X, minZoom); | |
camera.Zoom = Vector2.One * maxZoom; | |
// Set the initial target zoom value on game start | |
targetZoom = camera.Zoom.X; | |
} | |
public override void _PhysicsProcess(double delta) | |
{ | |
// Prevent zoom from becoming too fast when zooming out | |
zoomIncrement = zoomIncrementDefault * camera.Zoom.X; | |
// Lerp to the target zoom for a smooth effect | |
prevZoom = camera.Zoom; | |
camera.Zoom = camera.Zoom.Lerp( | |
to: new Vector2(targetZoom, targetZoom), | |
weight: smoothFactor); | |
if (prevZoom != camera.Zoom) | |
ZoomChanged?.Invoke(); | |
} | |
// Not sure if this should be done in _Input or _UnhandledInput | |
public override void _UnhandledInput(InputEvent @event) | |
{ | |
if (@event is InputEventMouseButton mouseButton) | |
InputEventMouseButton(mouseButton); | |
} | |
void InputEventMouseButton(InputEventMouseButton @event) | |
{ | |
HandleZoom(@event); | |
} | |
void HandleZoom(InputEventMouseButton @event) | |
{ | |
// Not sure why or if this is required | |
if (!@event.IsPressed()) | |
return; | |
// Zoom in | |
if (@event.ButtonIndex == MouseButton.WheelUp) | |
targetZoom += zoomIncrement; | |
// Zoom out | |
if (@event.ButtonIndex == MouseButton.WheelDown) | |
targetZoom -= zoomIncrement; | |
// Clamp the zoom | |
targetZoom = Mathf.Clamp(targetZoom, minZoom, MaxZoom); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment