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.
59 lines
1.8 KiB
C#
59 lines
1.8 KiB
C#
using UnityEngine;
|
|
|
|
public class CameraController : MonoBehaviour
|
|
{
|
|
[Header("Target")]
|
|
[SerializeField] Transform target;
|
|
|
|
[Header("Zoom Settings")]
|
|
[SerializeField] float baseDistance = 6f;
|
|
[SerializeField] float maxDistance = 12f;
|
|
[SerializeField] float zoomSpeed = 5f;
|
|
|
|
[Header("Follow Settings")]
|
|
[SerializeField] float followSmoothness = 5f;
|
|
[SerializeField] Vector3 heightOffset = new Vector3(0, 3f, 0); // optional vertical offset
|
|
|
|
private Rigidbody targetRb;
|
|
private float currentDistance;
|
|
public Camera mainCam;
|
|
private void Start()
|
|
{
|
|
Application.targetFrameRate = 120;
|
|
if (target == null)
|
|
{
|
|
Debug.LogError("CameraController: Target not assigned!");
|
|
enabled = false;
|
|
return;
|
|
}
|
|
|
|
targetRb = target.GetComponent<Rigidbody>();
|
|
if (targetRb == null)
|
|
{
|
|
Debug.LogError("CameraController: Target must have a Rigidbody.");
|
|
enabled = false;
|
|
return;
|
|
}
|
|
mainCam=GetComponent<Camera>();
|
|
currentDistance = baseDistance;
|
|
}
|
|
|
|
private void LateUpdate()
|
|
{
|
|
float speed = targetRb.velocity.magnitude;
|
|
|
|
// Zoom out based on speed
|
|
float targetDistance = Mathf.Lerp(baseDistance, maxDistance, speed / 30f);
|
|
currentDistance = Mathf.Lerp(currentDistance, targetDistance, Time.deltaTime * zoomSpeed);
|
|
|
|
// Calculate camera position: behind the target
|
|
Vector3 followPos = target.position + heightOffset - target.forward * currentDistance;
|
|
|
|
// Smoothly move camera
|
|
transform.position = Vector3.Lerp(transform.position, followPos, Time.deltaTime * followSmoothness);
|
|
|
|
// Look at the target (optional slight offset)
|
|
transform.LookAt(target.position + heightOffset * 0.5f);
|
|
}
|
|
}
|