Unity实现屏幕抖动效果(通过Camera Viewpoint实现)

由于游戏死亡时一般都需要屏幕抖一下下。
所以百度了下相关写法,发现方法很多~~~
找来找去,找到个简单粗暴地,啥都不需要,一个脚本拖动到Camera上就可以了
略微修改了一点点,share一下

using UnityEngine;
using System.Collections;

public class ShakeCamera : MonoBehaviour
{

    // 震动标志位
    private bool isshakeCamera = false;

    // 震动幅度
    public float shakeLevel = 3f;
    // 震动时间
    public float setShakeTime = 0.2f;
    // 震动的FPS
    public float shakeFps = 45f;

    private float fps;
    private float shakeTime = 0.0f;
    private float frameTime = 0.0f;
    private float shakeDelta = 0.005f;
    private Camera selfCamera;

    private Rect changeRect;

    void Awake()
    {
        selfCamera = GetComponent();
        changeRect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
    }

    // Use this for initialization
    void Start()
    {
        shakeTime = setShakeTime;
        fps = shakeFps;
        frameTime = 0.03f;
        shakeDelta = 0.005f;
    }

    // Update is called once per frame
    void Update()
    {
        if (isshakeCamera)
        {
            if (shakeTime > 0)
            {
                shakeTime -= Time.deltaTime;
                if (shakeTime <= 0)
                {
                    changeRect.xMin = 0.0f;
                    changeRect.yMin = 0.0f;
                    selfCamera.rect = changeRect;
                    isshakeCamera = false;
                    shakeTime = setShakeTime;
                    fps = shakeFps;
                    frameTime = 0.03f;
                    shakeDelta = 0.005f;
                }
                else
                {
                    frameTime += Time.deltaTime;

                    if (frameTime > 1.0 / fps)
                    {
                        frameTime = 0;
                        changeRect.xMin = shakeDelta * (-1.0f + shakeLevel * Random.value);
                        changeRect.yMin = shakeDelta * (-1.0f + shakeLevel * Random.value);
                        selfCamera.rect = changeRect;
                    }
                }
            }
        }
    }

    public void shake()
    {
        isshakeCamera = true;
    }
}

代码超级简单,就不写注释了... 三个public参数可以在unity界面配置
需要调试的话可以吧第一个参数的访问类型设置为public

转载于:https://www.cnblogs.com/coldcode/p/4772459.html

你可能感兴趣的:(Unity实现屏幕抖动效果(通过Camera Viewpoint实现))