2025-01-31 17:56:22 +08:00
|
|
|
using System.Collections;
|
|
|
|
using System.Collections.Generic;
|
|
|
|
using UnityEngine;
|
|
|
|
|
|
|
|
public class Followplayercam : MonoBehaviour
|
|
|
|
{
|
2025-02-05 15:56:52 +08:00
|
|
|
public Transform playerCamera;
|
|
|
|
public float distanceFromPlayer = 2.0f;
|
|
|
|
public float heightOffset = 0.0f;
|
|
|
|
public float positionSmoothFactor = 0.2f; // Adjust for responsiveness
|
|
|
|
public float rotationSmoothFactor = 0.2f;
|
2025-02-04 16:08:07 +08:00
|
|
|
|
2025-02-05 15:56:52 +08:00
|
|
|
private Vector3 smoothedPosition;
|
|
|
|
private Vector3 velocity = Vector3.zero;
|
2025-02-04 16:08:07 +08:00
|
|
|
|
|
|
|
void Start()
|
|
|
|
{
|
|
|
|
if (playerCamera == null)
|
|
|
|
{
|
|
|
|
Debug.LogError("Player Camera is not assigned!");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2025-02-05 15:56:52 +08:00
|
|
|
smoothedPosition = GetTargetPosition();
|
|
|
|
transform.position = smoothedPosition;
|
2025-02-04 16:08:07 +08:00
|
|
|
transform.rotation = GetTargetRotation();
|
|
|
|
}
|
2025-01-31 17:56:22 +08:00
|
|
|
|
2025-02-05 15:56:52 +08:00
|
|
|
void LateUpdate()
|
2025-01-31 17:56:22 +08:00
|
|
|
{
|
|
|
|
if (playerCamera != null)
|
|
|
|
{
|
2025-02-05 15:56:52 +08:00
|
|
|
Vector3 targetPosition = GetTargetPosition();
|
2025-02-04 16:08:07 +08:00
|
|
|
|
2025-02-05 15:56:52 +08:00
|
|
|
// SmoothDamp for a natural feel
|
|
|
|
smoothedPosition = Vector3.SmoothDamp(smoothedPosition, targetPosition, ref velocity, positionSmoothFactor);
|
|
|
|
transform.position = smoothedPosition;
|
2025-02-04 16:08:07 +08:00
|
|
|
|
2025-02-05 15:56:52 +08:00
|
|
|
// Exponential smoothing for rotation
|
|
|
|
transform.rotation = Quaternion.Slerp(transform.rotation, GetTargetRotation(), 1 - Mathf.Exp(-rotationSmoothFactor * Time.deltaTime * 10));
|
2025-01-31 17:56:22 +08:00
|
|
|
}
|
|
|
|
}
|
2025-02-04 16:08:07 +08:00
|
|
|
|
|
|
|
private Vector3 GetTargetPosition()
|
|
|
|
{
|
2025-02-05 15:56:52 +08:00
|
|
|
return playerCamera.position + playerCamera.forward * distanceFromPlayer + Vector3.up * heightOffset;
|
2025-02-04 16:08:07 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
private Quaternion GetTargetRotation()
|
|
|
|
{
|
|
|
|
Vector3 lookAtPoint = new Vector3(playerCamera.position.x, transform.position.y, playerCamera.position.z);
|
2025-02-05 15:56:52 +08:00
|
|
|
return Quaternion.LookRotation(lookAtPoint - transform.position);
|
2025-02-04 16:08:07 +08:00
|
|
|
}
|
2025-01-31 17:56:22 +08:00
|
|
|
}
|