やまめも

【 ゲーム開発・日々のことについて 】

カメラを振動

カメラを振動させる
Unity Tips and Tricks: Camera Shake

using UnityEngine;
using System.Collections;

public class CameraShake : MonoBehaviour {

	private Transform myTransform;
	private const float duration = 0.5f;
	private const float magnitude = 3;

	// --------------------------------------------
	private void Awake () {
		myTransform = transform;
	}


	private void OnEnable () {
//		EventsManager.onPlayerDieEvent += ShakeCamera;
	}

	
	private void OnDisable () {
//		EventsManager.onPlayerDieEvent -= ShakeCamera;
	}
	private void ShakeCamera () {
		switch (GameController.Instance.LevelGameState) {
		case GameController.GameState.GameOver :
		case GameController.GameState.GameOverUIFinished :
			break;
		default :
			StartCoroutine(Shake());
			break;
		}
	}
	private IEnumerator Shake() {
		
		float elapsed = 0.0f;
		
		Vector3 originalCamPos = myTransform.position;
		//duration = 継続時間
		//elapsed = 経過時間
		while (elapsed < duration) {
			//
			elapsed += Time.deltaTime;          
			//
			float percentComplete = elapsed / duration;         
			float damper = 1.0f - Mathf.Clamp(4.0f * percentComplete - 3.0f, 0.0f, 1.0f);
			
			// map noise to [-1, 1]
			float x = Random.value * 2.0f - 1.0f;
			float y = Random.value * 2.0f - 1.0f;
			x *= magnitude * damper;
			y *= magnitude * damper;

			myTransform.position = new Vector3(x, y, originalCamPos.z);
			
			yield return null;
		}
		
		myTransform.position = originalCamPos;
	}
}