今天想实现一下Unity中的相机抖动,又不想因为这么小的一个功能去找个插件,所以写了个很简单的代码实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| using System.Collections; using UnityEngine;
public class CameraShake : MonoBehaviour { public IEnumerator Shake(float duration, float magnitude) { Vector3 originalPosition = transform.position; float elapsed = 0.0f;
while (elapsed < duration) { float x = Random.Range(-1f, 1f) * magnitude; float y = Random.Range(-1f, 1f) * magnitude;
transform.position = new Vector3(originalPosition.x + x, originalPosition.y + y, originalPosition.z); elapsed += Time.deltaTime;
yield return null; }
transform.position = originalPosition; } }
|
把这段代码挂载在Camera上,之后在其他的脚本里使用下面方法调用就可以:
1 2 3 4 5 6
| public CameraShake cameraShake;
……
StartCoroutine(cameraShake.Shake(0.5f, 0.5f));
|