コガネブログ

平日更新を目標にUnityやC#、Visual Studioなどのゲーム開発アレコレを書いていきます

【Unity】カメラを揺らすスクリプト

ソースコード

using System.Collections;
using UnityEngine;

public class CameraShake : MonoBehaviour
{
    public void Shake( float duration, float magnitude )
    {
        StartCoroutine( DoShake( duration, magnitude ) );
    }

    private IEnumerator DoShake( float duration, float magnitude )
    {
        var pos = transform.localPosition;

        var elapsed = 0f;

        while ( elapsed < duration )
        {
            var x = pos.x + Random.Range( -1f, 1f ) * magnitude;
            var y = pos.y + Random.Range( -1f, 1f ) * magnitude;

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

            elapsed += Time.deltaTime;

            yield return null;
        }

        transform.localPosition = pos;
    }
}

使用例

using UnityEngine;

public class Example : MonoBehaviour
{
    public CameraShake shake;

    private void Update()
    {
        if ( Input.GetKeyDown( KeyCode.Z ) )
        {
            shake.Shake( 0.25f, 0.1f );
        }
    }
}

f:id:baba_s:20180305142249g:plain

参考動画