Smoother camera

This commit is contained in:
Иван Кузьменко 2023-08-16 20:46:41 +03:00
parent fdb4fc40cc
commit 51eb5aa15a

View file

@ -2,48 +2,54 @@ using Godot;
public partial class GameCamera : Camera2D public partial class GameCamera : Camera2D
{ {
[Export] public Player Player; [Export] public Player Player;
[Export] public Vector2 CameraBounds; [Export] public Vector2 CameraBounds = new(40, 30);
[Export] public Vector2 CameraFollowBounds = new(20, 10);
[Export] public float Speed = 0.5f;
/// <summary> /// <summary>
/// World position of the flashlight /// World position of the flashlight
/// </summary> /// </summary>
public Vector2 FlashlightPosition; public Vector2 FlashlightPosition;
public override void _PhysicsProcess(double delta) public override void _PhysicsProcess(double delta)
{ {
var relativePlayerPosition = Player.Position - Position; var difference = Vector2.Zero;
var halfCameraBounds = CameraBounds / 2;
float x = 0, y = 0;
if (relativePlayerPosition.X > halfCameraBounds.X)
{
x = relativePlayerPosition.X - halfCameraBounds.X;
}
else if (relativePlayerPosition.X < -halfCameraBounds.X)
{
x = relativePlayerPosition.X + halfCameraBounds.X;
}
if (relativePlayerPosition.Y > halfCameraBounds.Y)
{
y = relativePlayerPosition.Y - halfCameraBounds.Y;
}
else if (relativePlayerPosition.Y < -halfCameraBounds.Y)
{
y = relativePlayerPosition.Y + halfCameraBounds.Y;
}
var difference = new Vector2(x, y); var relativePlayerPosition = Player.Position - Position;
Position += difference; var halfCameraBounds = CameraBounds / 2;
FlashlightPosition += difference; var halfCameraFollowBounds = CameraFollowBounds / 2;
} var hardLimit = relativePlayerPosition.Clamp(-halfCameraBounds, halfCameraBounds);
difference = relativePlayerPosition - hardLimit;
GD.Print($"HardDiff {difference}");
if (difference.IsZeroApprox())
{
float x = 0, y = 0;
if (Mathf.Abs(relativePlayerPosition.X) >= halfCameraFollowBounds.X)
{
x = relativePlayerPosition.X * Speed * (float)delta;
}
public override void _Input(InputEvent @event) if (Mathf.Abs(relativePlayerPosition.Y) > halfCameraFollowBounds.Y)
{ {
base._Input(@event); y = relativePlayerPosition.Y * Speed * (float)delta;
}
if (@event is InputEventMouseMotion eventMouseMotion) difference = new Vector2(x, y);
{ GD.Print($"SmoothDiff {difference}");
FlashlightPosition = eventMouseMotion.Position - Constants.HalfScreenSize + Position; }
}
} Position = (Position + difference).Round();
FlashlightPosition = (FlashlightPosition + difference).Round();
}
public override void _Input(InputEvent @event)
{
base._Input(@event);
if (@event is InputEventMouseMotion eventMouseMotion)
{
FlashlightPosition = eventMouseMotion.Position - Constants.HalfScreenSize + Position;
}
}
} }