Code/CameraMovement.cs
using Sandbox;
using System;
using System.Numerics;
public sealed class CameraMovement : Component
{
// Properties
[Property] public GudeMovement Player { get; set; }
[Property] public GameObject Head { get; set; }
[Property] public float Distance { get; set; } = 300f;
[Property] public Vector3 CameraOffset { get; set; } = new Vector3(0, 0, 90);
[Property] public GameObject Body; //will reference the player game object's position
//[Property] public Vector3 CameraOffset { get; set; } = new Vector3( 300f, 0f, 155f ); //will set the offset position from the player to the camera
// Variables
public bool IsFirstPerson => Distance == 0f; // Helpful but not required. You could always just check if Distance == 0f
private CameraComponent Camera;
protected override void OnAwake()
{
//calculate the offset position between the camera and the player at the start of the game
// it subtracts the player's position from the camera's
//CameraOffset = WorldPosition - Body.WorldPosition;
Camera = Components.Get<CameraComponent>();
}
protected override void OnUpdate()
{
//sets the camera to where the player is plus the offset set above
//WorldPosition = Body.WorldPosition + CameraOffset;
//Rotate the head based on mouse movement
var eyeAngles = Head.WorldRotation.Angles();
eyeAngles.pitch += Input.MouseDelta.y * 0.1f;
eyeAngles.yaw -= Input.MouseDelta.x * 0.1f;
eyeAngles.roll = 0f;
eyeAngles.pitch = eyeAngles.pitch.Clamp( -89.9f, 89.9f );
Head.WorldRotation = eyeAngles.ToRotation();
Head.WorldPosition = Body.WorldPosition + CameraOffset;
if ( Camera is not null )
{
var camPos = Head.WorldPosition;
if ( !IsFirstPerson )
{
// Perform a trace backwards to see where we can safely place the camera
var camForward = eyeAngles.ToRotation().Forward;
var camTrace = Scene.Trace.Ray( camPos, camPos - (camForward * Distance) )
.WithoutTags( "player", "trigger" )
.Run();
if(camTrace.Hit)
{
camPos = camTrace.HitPosition + camTrace.Normal;
}
else
{
camPos = camTrace.EndPosition;
}
}
// Set the position of the camera to our calculated position
Camera.WorldPosition = camPos;
Camera.WorldRotation = eyeAngles.ToRotation();
}
}
}