unity3d 摄像机抖动效果 CameraShake

unity3d 摄像机抖动效果 ,利用脚本直接控制;当然也可以选择使用dotween插件,但到不至于为了使用仅一个功能,就导入了一个插件;

脚本示例:  

using UnityEngine;
using System.Collections;

public class CameraShake : MonoBehaviour 
{
    public Transform cameraTransform; 
    private Vector3 _currentPosition;        //记录抖动前的位置
    private float _shakeCD = 0.002f;        //抖动的频率
    private int _shakeCount = -1;            //设置抖动次数
    private float _shakeTime; 
    void Start ()
    {
        if(cameraTransform == null) cameraTransform = transform;
        
        _currentPosition = cameraTransform.position;    //记录抖动前的位置
        _shakeCount = Random.Range (50, 60);            //设置抖动次数
    } 
    void Update ()
    {
        if(_shakeTime + _shakeCD < Time.time && _shakeCount > 0)
        {
            _shakeCount --;
            float radio = Random.Range (-0.01f, 0.01f);
            
            if(_shakeCount == 1)    //抖动最后一次时设置为都动前记录的位置
                radio = 0;
            
            _shakeTime = Time.time;
            cameraTransform.position = _currentPosition + Vector3.one * radio;
        }
    }
}

 另一版本:

  

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// 
/// this Script need a Component Of camera
/// 
public class myCameraShake : MonoBehaviour { 
    private float m_FduringTime = 2.0f;
    [SerializeField]
    private bool m_BisOnShake = true;
    [SerializeField]
    private int  m_IyshakeLength =0;
    private Transform m_TCamera;
    private Vector3 m_OldPos;
    private float mtime = 0;
    void Awake()
    {
        if (this.transform.GetComponent() == null && GameObject.FindObjectOfType() == null)
        {
            Camera.main.gameObject.AddComponent();
        }
        m_TCamera = Camera.main.transform;
        m_OldPos = m_TCamera.position;
    }
    void Start ()
    {
        
    }
    private void Update()
    {
        if (m_BisOnShake)
        {
            mtime+=0.1f; 
            if (mtime < m_FduringTime)
            {
                m_IyshakeLength = Random.Range(-2, 4);
                if(m_IyshakeLength!=0)
                m_TCamera.position = Vector3.Lerp(m_OldPos, new Vector3(m_OldPos.x, m_OldPos.y + m_IyshakeLength, m_OldPos.z), 0.05f);
            }
            else
            {
                m_BisOnShake = !m_BisOnShake;
            }
        }
    } 
}

 

转载于:https://www.cnblogs.com/allyh/p/9193474.html

你可能感兴趣的:(游戏)