| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- using UnityEngine;
- public class CameraFollow : MonoBehaviour
- {
- [Header("跟随目标")]
- public Transform target;
- [Header("跟随参数")]
- public float distance = 10f;
- public float height = 5f;
- public float angle = 45f;
- public float smoothSpeed = 5f;
- [Header("视角参数")]
- public float lookAtHeightOffset = 1f;
- private Vector3 currentVelocity;
- private void LateUpdate()
- {
- if (target == null)
- {
- return;
- }
- float angleRad = angle * Mathf.Deg2Rad;
-
- float offsetX = -Mathf.Sin(angleRad) * distance;
- float offsetZ = -Mathf.Cos(angleRad) * distance;
- Vector3 targetPosition = target.position + new Vector3(offsetX, height, offsetZ);
- transform.position = Vector3.SmoothDamp(
- transform.position,
- targetPosition,
- ref currentVelocity,
- 1f / smoothSpeed
- );
- Vector3 lookAtPosition = target.position + Vector3.up * lookAtHeightOffset;
- transform.LookAt(lookAtPosition);
- }
- public void SetTarget(Transform newTarget)
- {
- target = newTarget;
- }
- public void SetAngle(float newAngle)
- {
- angle = newAngle;
- }
- public void SetDistance(float newDistance)
- {
- distance = newDistance;
- }
- public void SetHeight(float newHeight)
- {
- height = newHeight;
- }
- }
|