Code/Camera/SpringArm.cs
using Sandbox;
using System;
using System.Reflection.Metadata;
public sealed class SpringArm : Component
{
[Property] public GameObject TargetTransform { get; set; } //Object to follow.
[Property] public Vector3 Offset = new Vector3( 270, -4, 75 );
[Property] public float maxClamp = 85.0f;
[Property] public float minClamp = -85.0f;
[Property, Category( "Smoothers" )] private float CameraLerpSpeed = 10f;
public GameObject camera;
protected override void OnAwake()
{
//initial camera position.
camera = this.GameObject.Children[0]; //the camera is the first child of the pivot
if ( camera != null )
{
camera.LocalPosition = Offset;
}
}
protected override void OnUpdate()
{
HandlePosition();
HandleRotation( Input.AnalogLook.yaw, Input.AnalogLook.pitch );
}
public void HandlePosition()
{
if ( camera == null )
return;
WorldPosition = Vector3.Lerp(
WorldPosition,
TargetTransform.WorldPosition,
Time.Delta * CameraLerpSpeed
);
}
public void HandleRotation( float yaw, float pitch )
{
// Get current rotation in Euler angles
var angles = WorldRotation.Angles();
// Apply yaw normally
angles.yaw += yaw;
// Apply pitch and clamp
angles.pitch = Math.Clamp( angles.pitch + pitch, minClamp, maxClamp );
// Keep roll at 0
angles.roll = 0f;
// Reconstruct rotation
WorldRotation = Rotation.From( angles );
}
}