CameraShake 简单实现相机晃动效果

2016-8-17 雨辰 Unity3D

using UnityEngine;
using System.Collections;

public class CameraShake : MonoBehaviour
{
    // 抖动目标的transform(若未添加引用,怎默认为当前物体的transform)
    public Transform camTransform;
    //持续抖动的时长
    public float shake = 0.1f;
    public bool isShakeBool = false;
    // 抖动幅度(振幅)
    //振幅越大抖动越厉害
    public float shakeAmount = 0.5f;
    public float decreaseFactor = 0.5f;

    Vector3 originalPos;

    void Awake()
    {
        if (camTransform == null)
        {
            camTransform = GetComponent(typeof(Transform)) as Transform;
        }
    }

    void LateUpdate()
    {
        originalPos = camTransform.localPosition;
    }

    void Update()
    {
        if (!isShakeBool)
        {
            return;
        }

        if (shake > 0)
        {
            Vector3 shakePos = originalPos + Random.insideUnitSphere * shakeAmount;
            shakePos.z = -11.2f;
            camTransform.localPosition = shakePos;
            shake -= Time.deltaTime * decreaseFactor;
        }
        else
        {
            camTransform.localPosition = new Vector3(0, 0, -11.2f);
            isShakeBool = false;
            shake = 0.1f;
        }
    }

    public void ShowShake()
    {
        shake = 0.1f;
        isShakeBool = true;
    }
}

标签: Unity3D-优化性能 Unity3D

发表评论:

雨辰 joyimp|@2011-2018 京ICP备16030765号