Unity / C#
Beginner
Unity 2021.3+ / Unity 6
외부 패키지 없이 구현하는 감쇠 진폭 2D/3D 카메라 셰이크(Camera Shake)Dependency-Free Damped Amplitude 2D/3D Camera Shake Implementation
Perlin Noise와 지수 감쇠(Exponential Decay) 공식을 활용해 방향성 반동과 충격 강도를 자연스럽게 표현하는 경량 카메라 흔들림 컨트롤러.A lightweight camera shake controller using Perlin Noise and exponential trauma decay to express directional recoil and impact intensity.
#Unity #C# #Camera #Juice #Game Feel
핵심 개념단순
Random.insideUnitSphere로 카메라를 흔들면 진동이 거칠고 부자연스럽습니다. Mathf.PerlinNoise를 시간 축에 따라 샘플링하고 트라우마(Trauma) 값을 제곱/지수 감쇠시키면 부드러우면서도 자연스러운 타격감을 전달할 수 있습니다.Core ConceptShaking the camera with raw
Random.insideUnitSphere values produces harsh, erratic jitter. Sampling Mathf.PerlinNoise over time and applying quadratic or exponential decay to a trauma value delivers smooth and natural impact feedback.1. 카메라 셰이크 구현 코드1. Camera Shake Implementation Code
using UnityEngine;
public class CameraShake : MonoBehaviour
{
public static CameraShake Instance { get; private set; }
[SerializeField] private float frequency = 25f;
[SerializeField] private float maxAngle = 5f;
[SerializeField] private float maxOffset = 0.5f;
[SerializeField] private float decaySpeed = 1.5f;
private float _trauma = 0f;
private Vector3 _originalPos;
private float _timeCounter;
private void Awake()
{
Instance = this;
_originalPos = transform.localPosition;
}
public void Shake(float amount)
{
_trauma = Mathf.Clamp01(_trauma + amount);
}
private void LateUpdate()
{
if (_trauma > 0f)
{
_timeCounter += Time.deltaTime * frequency;
float shakeStrength = _trauma * _trauma; // 비선형 반응 (자연스러운 체감)
float offsetX = (Mathf.PerlinNoise(_timeCounter, 0f) * 2f - 1f) * maxOffset * shakeStrength;
float offsetY = (Mathf.PerlinNoise(0f, _timeCounter) * 2f - 1f) * maxOffset * shakeStrength;
float rotZ = (Mathf.PerlinNoise(_timeCounter, _timeCounter) * 2f - 1f) * maxAngle * shakeStrength;
transform.localPosition = _originalPos + new Vector3(offsetX, offsetY, 0f);
transform.localRotation = Quaternion.Euler(0f, 0f, rotZ);
_trauma = Mathf.MoveTowards(_trauma, 0f, Time.deltaTime * decaySpeed);
}
else
{
transform.localPosition = _originalPos;
transform.localRotation = Quaternion.identity;
}
}
}
using UnityEngine;
public class CameraShake : MonoBehaviour
{
public static CameraShake Instance { get; private set; }
[SerializeField] private float frequency = 25f;
[SerializeField] private float maxAngle = 5f;
[SerializeField] private float maxOffset = 0.5f;
[SerializeField] private float decaySpeed = 1.5f;
private float _trauma = 0f;
private Vector3 _originalPos;
private float _timeCounter;
private void Awake()
{
Instance = this;
_originalPos = transform.localPosition;
}
public void Shake(float amount)
{
_trauma = Mathf.Clamp01(_trauma + amount);
}
private void LateUpdate()
{
if (_trauma > 0f)
{
_timeCounter += Time.deltaTime * frequency;
float shakeStrength = _trauma * _trauma; // Non-linear response for natural falloff
float offsetX = (Mathf.PerlinNoise(_timeCounter, 0f) * 2f - 1f) * maxOffset * shakeStrength;
float offsetY = (Mathf.PerlinNoise(0f, _timeCounter) * 2f - 1f) * maxOffset * shakeStrength;
float rotZ = (Mathf.PerlinNoise(_timeCounter, _timeCounter) * 2f - 1f) * maxAngle * shakeStrength;
transform.localPosition = _originalPos + new Vector3(offsetX, offsetY, 0f);
transform.localRotation = Quaternion.Euler(0f, 0f, rotZ);
_trauma = Mathf.MoveTowards(_trauma, 0f, Time.deltaTime * decaySpeed);
}
else
{
transform.localPosition = _originalPos;
transform.localRotation = Quaternion.identity;
}
}
}
2. 파라미터 가이드2. Parameter Guide
좌우로 밀어서 표 전체 내용을 확인하세요
| 상황 | 권장 Shake Amount | 체감 효과 |
|---|---|---|
| 경미한 타격 / 권총 발사 | 0.2 ~ 0.3 | 가벼운 찰나의 반동 진동 |
| 근접 피격 / 폭발 주변 | 0.5 ~ 0.7 | 묵직한 화면 흔들림 및 회전 |
| 보스 피격 / 초대형 폭발 | 1.0 | 화면이 강하게 흔들리며 잔상 여운 |
Swipe horizontally to view the full table
| Scenario | Recommended Shake Amount | Perceived Effect |
|---|---|---|
| Light Hit / Pistol Fire | 0.2 ~ 0.3 | Brief, subtle recoil vibration |
| Melee Hit / Nearby Explosion | 0.5 ~ 0.7 | Heavy screen displacement and rotational tilt |
| Boss Hit / Massive Explosion | 1.0 | Strong screen shake with a lingering decay tail |
3. 실무 적용 및 주의사항3. Practical Application and Precautions
- 부모-자식 계층 분리: 카메라 이동 추적 로직이
transform.position을 매 프레임 덮어쓰지 않도록, 빈 부모 오브젝트(CameraRig)가 캐릭터를 추적하게 하고 자식 오브젝트(Main Camera)에서localPosition기준으로 셰이크를 적용합니다. - Perlin Noise 시드 오프셋 분리: X축, Y축, 회전(Z축) 샘플링 시 동일한 노이즈 좌표를 참조하면 대각선으로만 단조롭게 흔들리므로 각 축에 서로 다른 오프셋을 부여하는 것이 좋습니다.
- 사용자 멀미 방지 옵션 제공: 화면 흔들림에 민감한 플레이어를 위해 환경 설정에서 전체 셰이크 강도 배율(0% ~ 100%)을 조절할 수 있는 접근성 옵션을 두는 것이 권장됩니다.
- Separate Parent-Child Hierarchy: To prevent camera follow scripts from overwriting
transform.positioneach frame, have an empty parent object (CameraRig) follow the target while applying the shake tolocalPositionon the childMain Camera. - Decorrelate Perlin Noise Seed Offsets: Sampling the exact same noise coordinates for X, Y, and Z rotation causes repetitive diagonal motion, so assign distinct seed offsets to each axis.
- Provide an Accessibility Intensity Slider: Include a settings multiplier (0% to 100%) so players sensitive to motion sickness can reduce or disable screen shake.
트라우마 누적과 비선형 감쇠 기반의 카메라 셰이크를 적용하면, 작은 타격부터 강한 폭발까지 일관된 파라미터 체계로 타격 피드백을 제어할 수 있습니다.
Using trauma accumulation with non-linear decay lets you control impact feedback across light hits and heavy explosions under a single unified parameter model.