侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

unity3D实现摄像机抖动特效

技术  /  管理员 发布于 7年前   137

本文实例为大家分享了unity3D实现摄像机抖动的具体代码,供大家参考,具体内容如下

摄像机抖动特效 在需要的地方调用CameraShake.Shake()方法就可以

public class CameraShake : MonoBehaviour { ///  /// The cameras to shake. ///  public List cameras   = new List(); ///  /// The maximum number of shakes to perform. ///  public int numberOfShakes   = 2; ///  /// The amount to shake in each direction. ///  public Vector3 shakeAmount   = Vector3.one; ///  /// The amount to rotate in each direction. ///  public Vector3 rotationAmount   = Vector3.one; ///  /// The initial distance for the first shake. ///  public float distance   = 00.10f; ///  /// The speed multiplier for the shake. ///  public float speed   = 50.00f; ///  /// The decay speed (between 0 and 1). Higher values will stop shaking sooner. ///  public float decay   = 00.20f; ///  /// The modifier applied to speed in order to shake the GUI. ///  public float guiShakeModifier   = 01.00f; ///  /// If true, multiplies the final shake speed by the time scale. ///  public bool multiplyByTimeScale   = true;  // Shake rect (for GUI) private Rect shakeRect;  // States private bool shaking   = false; private bool cancelling   = false;  internal class ShakeState { internal readonly Vector3 startPosition; internal readonly Quaternion startRotation; internal readonly Vector2 guiStartPosition; internal Vector3 shakePosition; internal Quaternion shakeRotation; internal Vector2 guiShakePosition;  internal ShakeState(Vector3 position, Quaternion rotation, Vector2 guiPosition) { startPosition = position; startRotation = rotation; guiStartPosition = guiPosition; shakePosition = position; shakeRotation = rotation; guiShakePosition = guiPosition; } } private Dictionary> states = new Dictionary>(); private Dictionary shakeCount  = new Dictionary();  // Minimum shake values private const bool checkForMinimumValues  = true; private const float minShakeValue  = 0.001f; private const float minRotationValue  = 0.001f;  #region Singleton ///  /// The Camera Shake singleton instance. ///  public static CameraShake instance;  private void OnEnable() { if (cameras.Count < 1) { if (camera)  cameras.Add(camera); }  if (cameras.Count < 1) { if (Camera.main)  cameras.Add(Camera.main); }  if (cameras.Count < 1) { Debug.LogError("Camera Shake: No cameras assigned in the inspector!"); } instance = this; } #endregion  #region Static properties public static bool isShaking { get { return instance.IsShaking(); } } public static bool isCancelling { get { return instance.IsCancelling(); } } #endregion  #region Static methods public static void Shake() { instance.DoShake(); }  public static void Shake(int numberOfShakes, Vector3 shakeAmount, Vector3 rotationAmount, float distance, float speed, float decay, float guiShakeModifier, bool multiplyByTimeScale) { instance.DoShake(numberOfShakes, shakeAmount, rotationAmount, distance, speed, decay, guiShakeModifier, multiplyByTimeScale); } public static void Shake(System.Action callback) { instance.DoShake(callback); }  public static void Shake(int numberOfShakes, Vector3 shakeAmount, Vector3 rotationAmount, float distance, float speed, float decay, float guiShakeModifier, bool multiplyByTimeScale, System.Action callback) { instance.DoShake(numberOfShakes, shakeAmount, rotationAmount, distance, speed, decay, guiShakeModifier, multiplyByTimeScale, callback); } public static void CancelShake() { instance.DoCancelShake(); } public static void CancelShake(float time) { instance.DoCancelShake(time); }  public static void BeginShakeGUI() { instance.DoBeginShakeGUI(); } public static void EndShakeGUI() { instance.DoEndShakeGUI(); }  public static void BeginShakeGUILayout() { instance.DoBeginShakeGUILayout(); }  public static void EndShakeGUILayout() { instance.DoEndShakeGUILayout(); } #endregion  #region Events ///  /// Occurs when a camera starts shaking. ///  public event System.Action cameraShakeStarted;  ///  /// Occurs when a camera has completely stopped shaking and has been reset to its original position. ///  public event System.Action allCameraShakesCompleted; #endregion  #region Public methods public bool IsShaking() {  return shaking; } public bool IsCancelling() { return cancelling; } public void DoShake() { Vector3 seed = Random.insideUnitSphere;  foreach(Camera cam in cameras) { StartCoroutine(DoShake_Internal(cam, seed, this.numberOfShakes, this.shakeAmount, this.rotationAmount, this.distance, this.speed, this.decay, this.guiShakeModifier, this.multiplyByTimeScale, null)); } } public void DoShake(int numberOfShakes, Vector3 shakeAmount, Vector3 rotationAmount, float distance, float speed, float decay, float guiShakeModifier, bool multiplyByTimeScale) { Vector3 seed = Random.insideUnitSphere;  foreach(Camera cam in cameras) { StartCoroutine(DoShake_Internal(cam, seed, numberOfShakes, shakeAmount, rotationAmount, distance, speed, decay, guiShakeModifier, multiplyByTimeScale, null)); } } public void DoShake(System.Action callback) { Vector3 seed = Random.insideUnitSphere;  foreach(Camera cam in cameras) { StartCoroutine(DoShake_Internal(cam, seed, this.numberOfShakes, this.shakeAmount, this.rotationAmount, this.distance, this.speed, this.decay, this.guiShakeModifier, this.multiplyByTimeScale, callback)); } } public void DoShake(int numberOfShakes, Vector3 shakeAmount, Vector3 rotationAmount, float distance, float speed, float decay, float guiShakeModifier, bool multiplyByTimeScale, System.Action callback) { Vector3 seed = Random.insideUnitSphere;  foreach(Camera cam in cameras) { StartCoroutine(DoShake_Internal(cam, seed, numberOfShakes, shakeAmount, rotationAmount, distance, speed, decay, guiShakeModifier, multiplyByTimeScale, callback)); } } public void DoCancelShake() { if (shaking && !cancelling) { shaking = false; this.StopAllCoroutines(); foreach(Camera cam in cameras) {  if (shakeCount.ContainsKey(cam))  {  shakeCount[cam] = 0;  }  ResetState(cam.transform, cam); } } } public void DoCancelShake(float time) { if (shaking && !cancelling) { this.StopAllCoroutines(); this.StartCoroutine(DoResetState(cameras, shakeCount, time)); } } public void DoBeginShakeGUI() { CheckShakeRect(); GUI.BeginGroup(shakeRect); } public void DoEndShakeGUI() { GUI.EndGroup(); }  public void DoBeginShakeGUILayout() { CheckShakeRect(); GUILayout.BeginArea(shakeRect); }  public void DoEndShakeGUILayout() { GUILayout.EndArea(); } #endregion  #region Private methods private void OnDrawGizmosSelected() {  foreach(Camera cam in cameras) { if (!cam)  continue;  if (IsShaking()) {  Vector3 offset = cam.worldToCameraMatrix.GetColumn(3);  offset.z *= -1;  offset = cam.transform.position + cam.transform.TransformPoint(offset);  Quaternion rot = QuaternionFromMatrix(cam.worldToCameraMatrix.inverse * Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(1,1,-1)));  Matrix4x4 matrix = Matrix4x4.TRS(offset, rot, cam.transform.lossyScale);  Gizmos.matrix = matrix;  } else {  Matrix4x4 matrix = Matrix4x4.TRS(cam.transform.position, cam.transform.rotation, cam.transform.lossyScale);  Gizmos.matrix = matrix; }  Gizmos.DrawWireCube(Vector3.zero, shakeAmount);  Gizmos.color = Color.cyan;  if (cam.isOrthoGraphic) {  Vector3 pos = new Vector3(0, 0, (cam.near + cam.far) / 2f);  Vector3 size = new Vector3(cam.orthographicSize / cam.aspect, cam.orthographicSize * 2f, cam.far - cam.near);  Gizmos.DrawWireCube(pos, size); } else {  Gizmos.DrawFrustum(Vector3.zero, cam.fov, cam.far, cam.near, (.7f / cam.aspect)); } } }  private IEnumerator DoShake_Internal(Camera cam, Vector3 seed, int numberOfShakes, Vector3 shakeAmount, Vector3 rotationAmount, float distance, float speed, float decay, float guiShakeModifier, bool multiplyByTimeScale, System.Action callback) { // Wait for async cancel operations to complete if (cancelling) yield return null;  // Set random values var mod1 = seed.x > .5f ? 1 : -1; var mod2 = seed.y > .5f ? 1 : -1; var mod3 = seed.z > .5f ? 1 : -1;  // First shake if (!shaking) { shaking = true;  if (cameraShakeStarted != null)  cameraShakeStarted(); }  if (shakeCount.ContainsKey(cam)) shakeCount[cam]++; else shakeCount.Add(cam, 1);  // Pixel width is always based on the first camera float pixelWidth = GetPixelWidth(cameras[0].transform, cameras[0]);  // Set other values Transform cachedTransform = cam.transform; Vector3 camOffset = Vector3.zero; Quaternion camRot = Quaternion.identity;  int currentShakes = numberOfShakes; float shakeDistance = distance; float rotationStrength = 1;  float startTime = Time.time; float scale = multiplyByTimeScale ? Time.timeScale : 1; float pixelScale = pixelWidth * guiShakeModifier * scale; Vector3 start1 = Vector2.zero; Quaternion startR = Quaternion.identity; Vector2 start2 = Vector2.zero;  ShakeState state = new ShakeState(cachedTransform.position, cachedTransform.rotation, new Vector2(shakeRect.x, shakeRect.y)); List stateList;  if (states.TryGetValue(cam, out stateList)) { stateList.Add(state); } else { stateList = new List(); stateList.Add(state); states.Add(cam, stateList); }  // Main loop while (currentShakes > 0) {  if (checkForMinimumValues) {  // Early break when rotation is less than the minimum value.  if (rotationAmount.sqrMagnitude != 0 && rotationStrength <= minRotationValue)  break;    // Early break when shake amount is less than the minimum value.  if (shakeAmount.sqrMagnitude != 0 && distance != 0 && shakeDistance <= minShakeValue)  break; }  var timer = (Time.time - startTime) * speed;  state.shakePosition = start1 + new Vector3(  mod1 * Mathf.Sin(timer) * (shakeAmount.x * shakeDistance * scale),   mod2 * Mathf.Cos(timer) * (shakeAmount.y * shakeDistance * scale),   mod3 * Mathf.Sin(timer) * (shakeAmount.z * shakeDistance * scale));  state.shakeRotation = startR * Quaternion.Euler(  mod1 * Mathf.Cos(timer) * (rotationAmount.x * rotationStrength * scale),   mod2 * Mathf.Sin(timer) * (rotationAmount.y * rotationStrength * scale),   mod3 * Mathf.Cos(timer) * (rotationAmount.z * rotationStrength * scale));  state.guiShakePosition = new Vector2(  start2.x - (mod1 * Mathf.Sin(timer) * (shakeAmount.x * shakeDistance * pixelScale)),  start2.y - (mod2 * Mathf.Cos(timer) * (shakeAmount.y * shakeDistance * pixelScale)));  camOffset = GetGeometricAvg(stateList, true); camRot = GetAvgRotation(stateList);  NormalizeQuaternion(ref camRot);  Matrix4x4 m = Matrix4x4.TRS(camOffset, camRot, new Vector3(1, 1, -1));    cam.worldToCameraMatrix = m * cachedTransform.worldToLocalMatrix;  var avg = GetGeometricAvg(stateList, false);  shakeRect.x = avg.x; shakeRect.y = avg.y;  if (timer > Mathf.PI * 2) {  startTime = Time.time;  shakeDistance *= (1 - Mathf.Clamp01(decay));  rotationStrength *= (1 - Mathf.Clamp01(decay));  currentShakes--; } yield return null; }  // End conditions  shakeCount[cam]--;  // Last shake if (shakeCount[cam] == 0) { shaking = false; ResetState(cam.transform, cam);  if (allCameraShakesCompleted != null) {  allCameraShakesCompleted(); } } else { stateList.Remove(state); }  if (callback != null) callback(); } private Vector3 GetGeometricAvg(List states, bool position) {  float x = 0, y = 0, z = 0, l = states.Count;  foreach(ShakeState state in states) { if (position) {  x -= state.shakePosition.x;  y -= state.shakePosition.y;  z -= state.shakePosition.z; } else {  x += state.guiShakePosition.x;  y += state.guiShakePosition.y; } }  return new Vector3(x / l, y / l, z / l); }  private Quaternion GetAvgRotation(List states) { Quaternion avg = new Quaternion(0,0,0,0);  foreach(ShakeState state in states) { if (Quaternion.Dot (state.shakeRotation, avg) > 0) {  avg.x += state.shakeRotation.x;  avg.y += state.shakeRotation.y;  avg.z += state.shakeRotation.z;  avg.w += state.shakeRotation.w; } else {  avg.x += -state.shakeRotation.x;  avg.y += -state.shakeRotation.y;  avg.z += -state.shakeRotation.z;  avg.w += -state.shakeRotation.w; } }  var mag = Mathf.Sqrt(avg.x* avg.x + avg.y* avg.y + avg.z * avg.z + avg.w * avg.w);  if (mag > 0.0001f) { avg.x /= mag; avg.y /= mag; avg.z /= mag; avg.w /= mag; } else { avg = states[0].shakeRotation; }  return avg; } private void CheckShakeRect() { if (Screen.width != shakeRect.width || Screen.height != shakeRect.height) {  shakeRect.width = Screen.width; shakeRect.height = Screen.height; } } private float GetPixelWidth(Transform cachedTransform, Camera cachedCamera) { var position = cachedTransform.position; var screenPos = cachedCamera.WorldToScreenPoint(position - cachedTransform.forward * .01f); var offset = Vector3.zero;  if (screenPos.x > 0) offset = screenPos - Vector3.right; else offset = screenPos + Vector3.right;  if (screenPos.y > 0) offset = screenPos - Vector3.up; else offset = screenPos + Vector3.up;  offset = cachedCamera.ScreenToWorldPoint(offset);  return 1f / (cachedTransform.InverseTransformPoint(position) - cachedTransform.InverseTransformPoint(offset)).magnitude; } private void ResetState(Transform cachedTransform, Camera cam) { cam.ResetWorldToCameraMatrix();  shakeRect.x = 0; shakeRect.y = 0;  states[cam].Clear(); } private List offsetCache = new List(10); private List rotationCache = new List(10); private IEnumerator DoResetState(List cameras, Dictionary shakeCount, float time) { offsetCache.Clear(); rotationCache.Clear();  foreach(Camera cam in cameras) { offsetCache.Add((Vector3)((cam.worldToCameraMatrix * cam.transform.worldToLocalMatrix.inverse).GetColumn(3))); rotationCache.Add(QuaternionFromMatrix((cam.worldToCameraMatrix * cam.transform.worldToLocalMatrix.inverse).inverse * Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(1,1,-1))));  if (shakeCount.ContainsKey(cam)) {  shakeCount[cam] = 0; } states[cam].Clear(); }  float t = 0; float x = shakeRect.x, y = shakeRect.y; cancelling = true; while (t < time) { int i = 0; foreach(Camera cam in cameras) {  Transform cachedTransform = cam.transform;   shakeRect.x = Mathf.Lerp(x, 0, t / time);  shakeRect.y = Mathf.Lerp(y, 0, t / time);   Vector3 pos = Vector3.Lerp(offsetCache[i], Vector3.zero, t / time);  Quaternion rot = Quaternion.Slerp(rotationCache[i], cachedTransform.rotation, t / time);  Matrix4x4 m = Matrix4x4.TRS(pos, rot, new Vector3(1, 1, -1));   cam.worldToCameraMatrix = m * cachedTransform.worldToLocalMatrix;  i++; } t += Time.deltaTime; yield return null; }  foreach(Camera cam in cameras) { cam.ResetWorldToCameraMatrix(); shakeRect.x = 0; shakeRect.y = 0; } this.shaking = false; this.cancelling = false; } #endregion  #region Quaternion helpers private static Quaternion QuaternionFromMatrix(Matrix4x4 m) { return Quaternion.LookRotation(m.GetColumn(2), m.GetColumn(1)); } private static void NormalizeQuaternion (ref Quaternion q)  { float sum = 0;   for (int i = 0; i < 4; ++i) sum += q[i] * q[i];  float magnitudeInverse = 1 / Mathf.Sqrt(sum);  for (int i = 0; i < 4; ++i) q[i] *= magnitudeInverse; } #endregion }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    VMS中解协议常用方法备忘(小结)
    下一条:
    Unity UI拖拽模型选择功能
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 2024.07.09日OpenAI将终止对中国等国家和地区API服务(0个评论)
    • 2024/6/9最新免费公益节点SSR/V2ray/Shadowrocket/Clash节点分享|科学上网|免费梯子(0个评论)
    • 国外服务器实现api.openai.com反代nginx配置(0个评论)
    • 2024/4/28最新免费公益节点SSR/V2ray/Shadowrocket/Clash节点分享|科学上网|免费梯子(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-07
    • 2017-08
    • 2017-09
    • 2018-01
    • 2018-07
    • 2018-08
    • 2018-09
    • 2018-12
    • 2019-01
    • 2019-02
    • 2019-03
    • 2019-04
    • 2019-05
    • 2019-06
    • 2019-07
    • 2019-08
    • 2019-09
    • 2019-10
    • 2019-11
    • 2019-12
    • 2020-01
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2020-10
    • 2020-11
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-12
    • 2024-02
    • 2024-04
    • 2024-05
    • 2024-06
    • 2025-02
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客