xirang/Assets/scripts/camfollow.cs
杨号敬 5cce41cb28 add
2024-11-27 00:06:28 +08:00

33 lines
1.0 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class camfollow : MonoBehaviour
{
public Transform target; // 要跟随的目标,这里通常是玩家角色
public float smoothSpeed = 0.001f; // 摄像机移动的平滑速度
public Vector3 offset; // 摄像机相对于目标的偏移量
public float rotationSmoothSpeed = 50f; // 摄像机旋转的平滑速度
public float maxDistance = 10f; // 最大追踪距离s
public float minDistance = 5f; // 最小追踪距离
void LateUpdate()
{
if (target == null)
{
return;
}
// 计算目标位置
Vector3 desiredPosition = target.position + offset;
transform.position = desiredPosition;
// 计算摄像机旋转方向,平滑旋转到目标方向
Vector3 direction = target.position - transform.position;
Quaternion targetRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * rotationSmoothSpeed);
}
}