Unity笔记(9):Camera Shake【相机抖动】

续接上文的爆炸效果: 

Unity笔记(8):Use Particle System【粒子系统】_代码骑士的博客-CSDN博客

实现相机抖动效果

在相机挂载组件

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraShake : MonoBehaviour
{
    public IEnumerator Shake(float duration,float magnitude)//摇晃时间、幅度
    {
        Vector3 originalPos = transform.localPosition;//相机原始位置

        float elapsed = 0.0f;//摇晃进行时间
        while (elapsed < duration)
        {
            float x = Random.Range(-2f, 2f) * magnitude;//x轴随机抖动幅度
            float y = Random.Range(-2f, 2f) * magnitude;//y轴随机抖动幅度

            transform.localPosition = new Vector3(x, y, originalPos.z);

            elapsed += Time.deltaTime;

            yield return null;
        }
        transform.localPosition = originalPos;//再次复原
    }
}

在物体上增加代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Boom : MonoBehaviour
{
    public float delay = 3f;//爆炸前延时时间

    float countdown;//倒计时

    bool hasExploded = false;//确认是否爆炸

    public GameObject explosionEffect;

    public CameraShake cameraShake;

    void Start()
    {
        countdown = delay;
    }

    // Update is called once per frame
    void Update()
    {
        countdown -= Time.deltaTime;
        if (countdown <= 0f&&!hasExploded)
        {
            Explode();
            hasExploded = true;
        }
    }
    //爆破函数
    void Explode()
    {
        //显示爆炸效果
        Instantiate(explosionEffect, transform.position, transform.rotation);//实例化爆炸效果
        Destroy(gameObject);
        //相机抖动
        StartCoroutine(cameraShake.Shake(.25f,.5f));
    }
}

或者改为鼠标点击

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Boom : MonoBehaviour
{
    

    public ParticleSystem explosionEffect;

    public CameraShake cameraShake;

   
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            explosionEffect.Play();
            StartCoroutine(cameraShake.Shake(.25f, .5f));
        }
    }
   
}

相机挂载在新建空物体上(相机支架)

Unity笔记(9):Camera Shake【相机抖动】_第1张图片

然后将相机拖拽到物体脚本栏:

Unity笔记(9):Camera Shake【相机抖动】_第2张图片

你可能感兴趣的:(#,Unity实战教程,unity,游戏引擎)