59 lines
1.7 KiB
C#
59 lines
1.7 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; // 最小追踪距离
|
|
|
|
// 震动相关变量
|
|
public float shakeDuration = 0.5f; // 震动持续时间
|
|
public float shakeMagnitude = 1f; // 震动幅度
|
|
private Vector3 originalOffset; // 用于存储原始偏移量
|
|
private float shakeElapsedTime = 0f; // 记录震动已经持续的时间
|
|
void Start()
|
|
{
|
|
originalOffset = offset;
|
|
}
|
|
void LateUpdate()
|
|
{
|
|
if (target == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
// 震动逻辑处理
|
|
if (shakeElapsedTime > 0)
|
|
{
|
|
// 生成随机偏移量来模拟抖动
|
|
Vector3 randomOffset = Random.insideUnitSphere * shakeMagnitude;
|
|
offset = originalOffset + randomOffset;
|
|
|
|
shakeElapsedTime -= Time.deltaTime;
|
|
}
|
|
else
|
|
{
|
|
offset = originalOffset;
|
|
}
|
|
|
|
// 计算目标位置
|
|
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);
|
|
}
|
|
public void Shake()
|
|
{
|
|
shakeElapsedTime = shakeDuration;
|
|
}
|
|
}
|