Camera2D.cs

A 2D camera component for the game that updates the camera position each frame. It eases the camera toward TargetPos, applies a player camera shake offset, clamps the position to level bounds that depend on the player's zoom stat, and writes the result to WorldPosition. It also exposes SetPos to instantly place the camera.

Native Interop
using Sandbox;

public class Camera2D : Component
{
	[Property] public CameraComponent Camera { get; set; }

	public Vector2 TargetPos { get; set; }
	public Vector2 CameraPos { get; set; }

	protected override void OnUpdate()
	{
		base.OnUpdate();

		//Vector2 newPos = Vector2.Lerp( (Vector2)WorldPosition, TargetPos, Time.Delta * 3f );
		CameraPos = Utils.DynamicEaseTo( CameraPos, TargetPos, 0.2f, Time.Delta );

		var newPos = CameraPos + Utils.GetRandomVector() * Manager.Instance.Player.CamShakeAmount;

		float bounds_zoom = 1f + Manager.Instance.Player.Stats[PlayerStat.ZoomAmount] * 0.44f;
		var XDIST = 10.75f / bounds_zoom;
		var Y_MIN = -8.8f / bounds_zoom;
		var Y_MAX = 8.9f / bounds_zoom;
		newPos = new Vector2( MathX.Clamp( newPos.x, -XDIST, XDIST ), MathX.Clamp( newPos.y, Y_MIN, Y_MAX ) );

		WorldPosition = ((Vector3)newPos).WithZ( WorldPosition.z );
	}

	public void SetPos( Vector2 pos )
	{
		CameraPos = pos;
		TargetPos = pos;
		WorldPosition = ((Vector3)pos).WithZ( WorldPosition.z );
	}
}