using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FreeCameraShake: SingletonMono<FreeCameraShake>
{
private Transform ThisTrasform = null;
//总共抖动时间
private float ShakeTime = 2.0f;
//在任何方向上偏移的距离
private float ShakeAmount = 400.0f;
//相机移动到震动点的速度
private float ShakeSpeed = 3.0f;
private Action myAction;
public void StartShake(Action action)
{
myAction = action;
ThisTrasform = GetComponent<Transform>();
//开始震动
StartCoroutine(OnShake());
}
public IEnumerator OnShake()
{
Debug.Log("开始震动");
//存下当前相机位置
Vector3 OrigPosition = ThisTrasform.localPosition;
//记下运行时间
float ElapsedTime = 0.0f;
//重复此步骤以获得总震动时间
while (ElapsedTime < ShakeTime)
{
//在单位球上随机取点
Vector3 RandomPoint = OrigPosition + UnityEngine.Random.insideUnitSphere * ShakeAmount;
//更新相机位置
ThisTrasform.localPosition = Vector3.Lerp(ThisTrasform.localPosition, RandomPoint, Time.deltaTime * ShakeSpeed);
yield return null;
//更新时间
ElapsedTime += Time.deltaTime;
}
Debug.Log("震动结束");
//恢复相机位置
ThisTrasform.localPosition = OrigPosition;
myAction.Invoke();
}
}
翻译地址:
该代码挂在摄像机即可
选自《Unity脚本设计》