A scene component that positions an orthographic top-down camera to follow a local player. It finds the main CameraComponent and local PlayerController on start, disables player camera/look controls, sets orthographic mode and height, and each update places the camera at a fixed offset and orients it to look at the player.
using Sandbox;
using System.Linq;
public sealed class TopDownCameraFollow : Component
{
[Property] public Vector3 CameraOffset { get; set; } = new Vector3( -500f, -500f, 1200f );
[Property] public float OrthographicHeight { get; set; } = 1400f;
private CameraComponent _camera;
private PlayerController _localPlayer;
protected override void OnStart()
{
_camera = Scene.GetAllComponents<CameraComponent>().FirstOrDefault( camera => camera.IsMainCamera );
if ( _camera.IsValid() )
{
_camera.Orthographic = true;
_camera.OrthographicHeight = OrthographicHeight;
}
_localPlayer = Scene.GetAllComponents<PlayerController>()
.FirstOrDefault( player => player.IsValid() && !player.IsProxy && player.GameObject.IsValid() );
if ( _localPlayer.IsValid() )
{
_localPlayer.UseCameraControls = false;
_localPlayer.UseLookControls = false;
}
}
protected override void OnUpdate()
{
if ( IsProxy ) return;
if ( !_camera.IsValid() || !_localPlayer.IsValid() ) return;
Vector3 targetPosition = _localPlayer.WorldPosition;
Vector3 cameraPosition = targetPosition + CameraOffset;
_camera.GameObject.WorldPosition = cameraPosition;
_camera.GameObject.WorldRotation = Rotation.LookAt( targetPosition - cameraPosition );
}
}