You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Driftology/Assets/Scripts/CameraController.cs

87 lines
2.8 KiB
C#

2 months ago
using UnityEngine;
2 months ago
[RequireComponent(typeof(Camera))]
public class CameraController : MonoBehaviour
2 months ago
{
[Header("Target")]
2 months ago
[Tooltip("If set, camera will follow this Transform. Otherwise it will auto-find the local player.")]
[SerializeField] private Transform target;
2 months ago
[Header("Zoom Settings")]
2 months ago
[SerializeField] private float baseDistance = 6f;
[SerializeField] private float maxDistance = 12f;
[SerializeField] private float zoomSpeed = 5f;
2 months ago
[Header("Follow Settings")]
2 months ago
[SerializeField] private float followSmoothness = 5f;
[SerializeField] private Vector3 heightOffset = new Vector3(0, 3f, 0);
2 months ago
private Rigidbody targetRb;
private float currentDistance;
private Camera cam;
2 months ago
private void Start()
{
2 months ago
Application.targetFrameRate = 120;
cam = GetComponent<Camera>();
2 months ago
currentDistance = baseDistance;
2 months ago
if (target != null)
2 months ago
{
2 months ago
// User assigned a target in the Inspector
InitializeTarget();
}
else
{
// No target assigned, try to auto-find after a short delay
Invoke(nameof(FindLocalPlayer), 0.5f);
2 months ago
}
2 months ago
}
2 months ago
2 months ago
private void InitializeTarget()
{
2 months ago
targetRb = target.GetComponent<Rigidbody>();
if (targetRb == null)
{
2 months ago
Debug.LogError("CameraController: Assigned target has no Rigidbody component.", this);
2 months ago
enabled = false;
return;
}
2 months ago
Debug.Log("CameraController: Following manually assigned target.", this);
}
private void FindLocalPlayer()
{
foreach (var vehicle in FindObjectsOfType<VehicleController>())
{
// VehicleController inherits NetworkBehaviour, so .Object is the NetworkObject
if (vehicle.Object != null && vehicle.Object.HasInputAuthority)
{
target = vehicle.FollowTarget;
InitializeTarget();
Debug.Log("CameraController: Auto-found local player to follow.", this);
return;
}
}
Debug.LogWarning("CameraController: No local player found to follow <20> disabling.", this);
enabled = false;
2 months ago
}
private void LateUpdate()
{
2 months ago
if (target == null || targetRb == null) return;
2 months ago
2 months ago
float speed = targetRb.velocity.magnitude;
2 months ago
float targetDistance = Mathf.Lerp(baseDistance, maxDistance, speed / 30f);
currentDistance = Mathf.Lerp(currentDistance, targetDistance, Time.deltaTime * zoomSpeed);
2 months ago
Vector3 followPos = target.position
+ heightOffset
- target.forward * currentDistance;
2 months ago
transform.position = Vector3.Lerp(transform.position, followPos, Time.deltaTime * followSmoothness);
transform.LookAt(target.position + heightOffset * 0.5f);
}
}