1bit-game-jam/scripts/GameCamera.cs

66 lines
1.9 KiB
C#

using System.Diagnostics;
using Godot;
public partial class GameCamera : Camera2D
{
[Export] public Player Player;
[Export] public Vector2 CameraBounds = new(40, 30);
[Export] public Vector2 CameraFollowBounds = new(20, 10);
[Export] public float Speed = 0.5f;
[Export] public VirtualCursor Cursor;
[Export] public const float CursorSpeed = 2.0f;
/// <summary>
/// World position of the flashlight
/// </summary>
public Vector2 FlashlightPosition;
public override void _PhysicsProcess(double delta)
{
Vector2 direction = Input.GetVector("cursor_left", "cursor_right", "cursor_up", "cursor_down");
if (direction != Vector2.Zero)
{
FlashlightPosition += direction * CursorSpeed;
}
var difference = Vector2.Zero;
var relativePlayerPosition = Player.Position - Position;
var halfCameraBounds = CameraBounds / 2;
var halfCameraFollowBounds = CameraFollowBounds / 2;
var hardLimit = relativePlayerPosition.Clamp(-halfCameraBounds, halfCameraBounds);
difference = relativePlayerPosition - hardLimit;
if (difference.IsZeroApprox())
{
float x = 0, y = 0;
if (Mathf.Abs(relativePlayerPosition.X) >= halfCameraFollowBounds.X)
{
x = relativePlayerPosition.X * Speed * (float)delta;
}
if (Mathf.Abs(relativePlayerPosition.Y) > halfCameraFollowBounds.Y)
{
y = relativePlayerPosition.Y * Speed * (float)delta;
}
difference = new Vector2(x, y);
}
Position = (Position + difference).Round();
FlashlightPosition = (FlashlightPosition + difference).Round();
Cursor.Position = FlashlightPosition;
}
public override void _Input(InputEvent @event)
{
base._Input(@event);
if (@event is InputEventMouseMotion eventMouseMotion)
{
FlashlightPosition = eventMouseMotion.Position - Constants.HalfScreenSize + Position;
//Cursor.Position = eventMouseMotion.Position - Constants.HalfScreenSize + Position;
}
}
}