44 lines
1.0 KiB
C#
44 lines
1.0 KiB
C#
using System.Collections;
|
|
using UnityEngine;
|
|
using UnityEngine.InputSystem;
|
|
|
|
public class CameraShakeTrigger : MonoBehaviour
|
|
{
|
|
private Vector3 originalPos;
|
|
|
|
void Awake()
|
|
{
|
|
originalPos = transform.localPosition;
|
|
}
|
|
private void Update()
|
|
{
|
|
if (Mouse.current.leftButton.wasPressedThisFrame)
|
|
{
|
|
TriggerShake();
|
|
}
|
|
}
|
|
public void TriggerShake(float duration = 0.3f, float magnitude = 0.2f)
|
|
{
|
|
StopAllCoroutines(); // 避免叠加
|
|
StartCoroutine(Shake(duration, magnitude));
|
|
}
|
|
|
|
private IEnumerator Shake(float duration, float magnitude)
|
|
{
|
|
float elapsed = 0.0f;
|
|
|
|
while (elapsed < duration)
|
|
{
|
|
float x = Random.Range(-1f, 1f) * magnitude;
|
|
float y = Random.Range(-1f, 1f) * magnitude;
|
|
|
|
transform.localPosition = new Vector3(originalPos.x + x, originalPos.y + y, originalPos.z);
|
|
|
|
elapsed += Time.deltaTime;
|
|
yield return null;
|
|
}
|
|
|
|
transform.localPosition = originalPos;
|
|
}
|
|
}
|