components/spectator.cs

A spectator controller component for the game that moves a free camera based on mouse and keyboard input. It reads mouse delta and WASD/space/shift keys to rotate and translate a camera GameObject, and sets camera FOV from preferences.

Native Interop
using Sandbox;

public class Spectator : Component
{
    GameObject c;
    protected override void OnStart()
    {if (IsProxy) return;
    c = Scene.Camera.GameObject;}
    
    float x;
    float y;
    float z;
    
    protected override void OnUpdate()
    { if (IsProxy || new Game.Overlay().IsPauseMenuOpen) return;
        var Delta = Input.MouseDelta * Time.Delta * Preferences.Sensitivity;
        
        x += Delta.x;
        y -= Delta.y;
        y = y.Clamp(-89, 89);
        
        c.WorldPosition = WorldPosition;
        c.WorldRotation = new Angles(-y, -x, 0);
        
        z = Time.Delta; z *= Input.Down("shift") ? 400 : 200;
        if (Input.Down("w")) WorldPosition += c.WorldRotation * new Vector3(z, 0, 0);
        if (Input.Down("s")) WorldPosition += c.WorldRotation * new Vector3(-z, 0, 0);
        if (Input.Down("a")) WorldPosition += c.WorldRotation * new Vector3(0, z, 0);
        if (Input.Down("d")) WorldPosition += c.WorldRotation * new Vector3(0, -z, 0);
        if (Input.Down("space")) WorldPosition += c.WorldRotation * new Vector3(0, 0, z);
    c.GetComponent<CameraComponent>().FieldOfView = Preferences.FieldOfView;}
}