Unity / C#
Beginner
Unity 2021.3+ / Unity 6
2D 패럴랙스 스크롤링(Parallax Scrolling) 다중 배경과 무한 루프 재배치2D Parallax Scrolling Multi-Layer Backgrounds and Infinite Loop Repositioning
카메라 이동량에 따른 Z-깊이별 레이어 상대 속도 연산, 뷰포트 경계를 벗어난 타일 배경의 무한 랩핑(Infinite Wrapping) 구현.Calculating relative layer velocities by depth based on camera movement and implementing infinite wrapping for tiled backgrounds outside the viewport.
#Unity #2D #Parallax #Background #Camera #Environment
핵심 개념2D 횡스크롤 게임에서 입체감을 표현하는 대표적인 방법은 원거리 배경(산, 구름)은 천천히 움직이고 근경(가로등, 풀숲)은 빠르게 움직이게 하는 패럴랙스 스크롤링(Parallax Scrolling)입니다. 스프라이트의 가로 폭을 측정해 카메라가 지나갈 때마다 위치를 재배치하면 무한 반복 배경을 구성할 수 있습니다.
Core ConceptA common way to convey depth in 2D side-scrolling games is Parallax Scrolling, where distant backgrounds (mountains, clouds) move slowly while foreground elements (streetlights, bushes) move faster relative to the camera. By measuring the horizontal width of a sprite and snapping its position as the camera passes, you can build an infinitely repeating background.
1. 무한 패럴랙스 레이어 스크립트1. Infinite Parallax Layer Script
using UnityEngine;
public class ParallaxLayer : MonoBehaviour
{
[Tooltip("0 = 카메라와 동기화(먼 배경), 1 = 고정")]
[SerializeField] private Vector2 parallaxEffectMultiplier = new Vector2(0.5f, 0.1f);
[SerializeField] private bool infiniteHorizontal = true;
private Transform _cameraTransform;
private Vector3 _lastCameraPosition;
private float _textureUnitSizeX;
private void Start()
{
if (Camera.main != null)
_cameraTransform = Camera.main.transform;
_lastCameraPosition = _cameraTransform.position;
// 스프라이트 렌더러의 가로 크기 측정
SpriteRenderer sprite = GetComponent<SpriteRenderer>();
if (sprite != null)
{
_textureUnitSizeX = sprite.bounds.size.x;
}
}
private void LateUpdate()
{
if (_cameraTransform == null) return;
Vector3 deltaMovement = _cameraTransform.position - _lastCameraPosition;
// 카메라 이동량에 효과 배율 적용
transform.position += new Vector3(
deltaMovement.x * parallaxEffectMultiplier.x,
deltaMovement.y * parallaxEffectMultiplier.y,
0f
);
_lastCameraPosition = _cameraTransform.position;
// 무한 가로 루프 처리
if (infiniteHorizontal && _textureUnitSizeX > 0f)
{
float offsetFromCamera = _cameraTransform.position.x - transform.position.x;
if (Mathf.Abs(offsetFromCamera) >= _textureUnitSizeX)
{
float offsetPositionX = (offsetFromCamera > 0) ? _textureUnitSizeX : -_textureUnitSizeX;
transform.position = new Vector3(transform.position.x + offsetPositionX, transform.position.y, transform.position.z);
}
}
}
}
using UnityEngine;
public class ParallaxLayer : MonoBehaviour
{
[Tooltip("0 = moves with camera (far background), 1 = stationary")]
[SerializeField] private Vector2 parallaxEffectMultiplier = new Vector2(0.5f, 0.1f);
[SerializeField] private bool infiniteHorizontal = true;
private Transform _cameraTransform;
private Vector3 _lastCameraPosition;
private float _textureUnitSizeX;
private void Start()
{
if (Camera.main != null)
_cameraTransform = Camera.main.transform;
_lastCameraPosition = _cameraTransform.position;
// Measure the horizontal bounds of the SpriteRenderer
SpriteRenderer sprite = GetComponent<SpriteRenderer>();
if (sprite != null)
{
_textureUnitSizeX = sprite.bounds.size.x;
}
}
private void LateUpdate()
{
if (_cameraTransform == null) return;
Vector3 deltaMovement = _cameraTransform.position - _lastCameraPosition;
// Apply the parallax multiplier to the camera delta
transform.position += new Vector3(
deltaMovement.x * parallaxEffectMultiplier.x,
deltaMovement.y * parallaxEffectMultiplier.y,
0f
);
_lastCameraPosition = _cameraTransform.position;
// Handle infinite horizontal wrapping
if (infiniteHorizontal && _textureUnitSizeX > 0f)
{
float offsetFromCamera = _cameraTransform.position.x - transform.position.x;
if (Mathf.Abs(offsetFromCamera) >= _textureUnitSizeX)
{
float offsetPositionX = (offsetFromCamera > 0) ? _textureUnitSizeX : -_textureUnitSizeX;
transform.position = new Vector3(transform.position.x + offsetPositionX, transform.position.y, transform.position.z);
}
}
}
}
2. 다중 레이어 깊이 권장 계수2. Recommended Multi-Layer Depth Multipliers
좌우로 밀어서 표 전체 내용을 확인하세요
| 레이어 종류 | X 패럴랙스 계수 | Y 패럴랙스 계수 | 스프라이트 Sorting Layer |
|---|---|---|---|
| 초원거리 (달, 먼 하늘) | 0.95 ~ 0.99 | 0.98 | Background_Sky |
| 원거리 (먼 산, 빌딩 숲) | 0.70 ~ 0.85 | 0.50 | Background_Distant |
| 중거리 (나무, 울타리) | 0.40 ~ 0.60 | 0.20 | Background_Mid |
| 플레이어 활동 지형 | 0.00 (직접 이동) | 0.00 | Default / Ground |
| 근경 (전방 풀숲, 가로등) | -0.20 ~ -0.40 | -0.10 | Foreground |
Swipe horizontally to view the full table
| Layer Type | X Parallax Factor | Y Parallax Factor | Sprite Sorting Layer |
|---|---|---|---|
| Extreme Far (Moon, Sky) | 0.95 ~ 0.99 | 0.98 | Background_Sky |
| Far (Distant Mountains, Skyline) | 0.70 ~ 0.85 | 0.50 | Background_Distant |
| Midground (Trees, Fences) | 0.40 ~ 0.60 | 0.20 | Background_Mid |
| Player Playfield Terrain | 0.00 (Direct Movement) | 0.00 | Default / Ground |
| Foreground (Front Bushes, Lamps) | -0.20 ~ -0.40 | -0.10 | Foreground |
3. 렌더링 최적화 팁3. Rendering Optimization Tips
Draw Mode = Tiled활용: 텍스처 임포트 설정에서Wrap Mode = Repeat로 설정하고 SpriteRenderer의Draw Mode를Tiled로 지정하면 단일 스프라이트로 넓은 영역을 채울 수 있습니다.LateUpdate사용: 패럴랙스 연산을Update에서 실행하면 카메라 추적과 프레임 타이밍이 어긋나 배경 스프라이트 경계면에 틈새가 보이는 현상이 발생할 수 있습니다.
- Use
Draw Mode = Tiled: SetWrap Mode = Repeatin the texture import settings and set the SpriteRenderer'sDraw ModetoTiledso a single sprite can cover a wide area. - Run in
LateUpdate: Executing parallax calculations inUpdatecan cause timing mismatches with camera tracking, resulting in 1-pixel seams between background sprite edges.
카메라 이동에 맞춘 레이어별 속도 차등 적용과 타일 재배치 로직을 결합하면, 적은 수의 배경 리소스로도 깊이감 있는 2D 스테이지 환경을 구성할 수 있습니다.
Combining depth-based velocity multipliers with tile repositioning allows you to construct a layered 2D stage environment with a small set of background assets.