Unity/3d/カメラを揺らす
提供: 初心者エンジニアの簡易メモ
using System.Collections; using System.Collections.Generic; 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; } }
使い方
private void ExecCameraShake() { CameraShake shake = GameObject.Find("FPS Camera").GetComponent<CameraShake>(); shake.Shake(0.3f, 0.025f); } 参考:https://baba-s.hatenablog.com/entry/2018/03/14/170400