Unity / C#
Advanced
Unity 2022.3+ / Unity 6
3D 애니메이션 모델의 8방향 2D 픽셀 스프라이트 & 노멀맵 자동 베이킹(Baking) 툴Automated 8-Directional 2D Pixel Sprite & Normal Map Baker from 3D Animated Models
Dead Cells 및 Factorio 제작 방식: 3D 모델과 본 애니메이션을 지정된 각도·프레임별로 캡처해 2D 픽셀 스프라이트 시트와 노멀맵 PNG를 자동 굽는 에디터 툴.An Editor tool inspired by Dead Cells and Factorio that captures 3D models and skeletal animations across angles and frames to bake 2D pixel sprite sheets.
#Unity #Editor #SpriteSheet #Baker #3D-to-2D #Tool
핵심 개념복잡한 3D 갑옷 캐릭터의 8방향 걷기·공격 모션을 2D 도트로 직접 작업하는 데는 많은 시간이 소요됩니다. *Dead Cells*와 *Factorio* 개발팀은 3D 모델에 모션 캡처나 3D 애니메이션을 적용한 뒤, 에디터 스크립트로 8개 각도에서 저해상도로 자동 캡처하여 2D 스프라이트 시트로 구워내는 파이프라인을 구축해 에셋 제작 기간을 단축했습니다.
Core ConceptHand-drawing 8-directional walk and attack animations for complex armored characters in 2D pixel art requires substantial time. The development teams behind *Dead Cells* and *Factorio* shortened asset production time by applying animations to 3D models and using scripts to capture them at low resolution from 8 angles into 2D sprite sheets.
1. 3D-to-2D 스프라이트 시트 자동 베이커 에디터 스크립트1. 3D-to-2D Sprite Sheet Baker Editor Script
#if UNITY_EDITOR
using System.IO;
using UnityEditor;
using UnityEngine;
public class SpriteSheetBakerWindow : EditorWindow
{
[SerializeField] private GameObject targetModel;
[SerializeField] private AnimationClip clipToBake;
[SerializeField] private int frameRate = 12; // 레트로 도트 프레임 (12fps)
[SerializeField] private int resolution = 64; // 프레임당 해상도 (64x64)
[SerializeField] private int directionCount = 8; // 8방향
[MenuItem("Tools/LYSC/3D to 2D Sprite Baker")]
public static void ShowWindow()
{
GetWindow<SpriteSheetBakerWindow>("Sprite Baker");
}
private void OnGUI()
{
GUILayout.Label("3D 모델 -> 2D 픽셀 스프라이트 시트 베이커", EditorStyles.boldLabel);
targetModel = (GameObject)EditorGUILayout.ObjectField("3D 모델 프리팹", targetModel, typeof(GameObject), true);
clipToBake = (AnimationClip)EditorGUILayout.ObjectField("애니메이션 클립", clipToBake, typeof(AnimationClip), false);
frameRate = EditorGUILayout.IntSlider("베이킹 FPS", frameRate, 6, 24);
resolution = EditorGUILayout.IntField("스프라이트 해상도 (px)", resolution);
directionCount = EditorGUILayout.IntPopup("방향 수", directionCount, new[] { "1방향", "4방향", "8방향" }, new[] { 1, 4, 8 });
if (GUILayout.Button("스프라이트 시트 베이킹 시작", GUILayout.Height(35)))
{
BakeSpriteSheet();
}
}
private void BakeSpriteSheet()
{
if (targetModel == null || clipToBake == null)
{
EditorUtility.DisplayDialog("오류", "모델과 클립을 모두 등록해야 합니다.", "확인");
return;
}
int totalFrames = Mathf.CeilToInt(clipToBake.length * frameRate);
int sheetWidth = totalFrames * resolution;
int sheetHeight = directionCount * resolution;
Texture2D sheet = new Texture2D(sheetWidth, sheetHeight, TextureFormat.RGBA32, false);
// 캡처용 임시 카메라 및 렌더텍스처 구성
GameObject camObj = new GameObject("TempBakeCamera");
Camera bakeCam = camObj.AddComponent<Camera>();
bakeCam.orthographic = true;
bakeCam.orthographicSize = 1.0f;
bakeCam.clearFlags = CameraClearFlags.SolidColor;
bakeCam.backgroundColor = new Color(0, 0, 0, 0);
RenderTexture rt = new RenderTexture(resolution, resolution, 24, RenderTextureFormat.ARGB32)
{
filterMode = FilterMode.Point
};
bakeCam.targetTexture = rt;
// 각도별, 프레임별 샘플링
for (int dir = 0; dir < directionCount; dir++)
{
float angle = dir * (360f / directionCount);
targetModel.transform.rotation = Quaternion.Euler(0f, angle, 0f);
for (int f = 0; f < totalFrames; f++)
{
float time = (float)f / frameRate;
clipToBake.SampleAnimation(targetModel, time);
// 카메라 렌더링
bakeCam.Render();
// 픽셀 복사
RenderTexture.active = rt;
Texture2D tempFrame = new Texture2D(resolution, resolution, TextureFormat.RGBA32, false);
tempFrame.ReadPixels(new Rect(0, 0, resolution, resolution), 0, 0);
tempFrame.Apply();
// 시트에 복사 (행: 방향, 열: 프레임)
int startX = f * resolution;
int startY = (directionCount - 1 - dir) * resolution;
sheet.SetPixels(startX, startY, resolution, resolution, tempFrame.GetPixels());
}
}
sheet.Apply();
// PNG 파일 저장
byte[] bytes = sheet.EncodeToPNG();
string path = Path.Combine(Application.dataPath, $"{targetModel.name}_{clipToBake.name}_Sheet.png");
File.WriteAllBytes(path, bytes);
AssetDatabase.Refresh();
// 정리
bakeCam.targetTexture = null;
RenderTexture.active = null;
DestroyImmediate(camObj);
rt.Release();
EditorUtility.DisplayDialog("완료", $"스프라이트 시트가 생성되었습니다:
{path}", "확인");
}
}
#endif
#if UNITY_EDITOR
using System.IO;
using UnityEditor;
using UnityEngine;
public class SpriteSheetBakerWindow : EditorWindow
{
[SerializeField] private GameObject targetModel;
[SerializeField] private AnimationClip clipToBake;
[SerializeField] private int frameRate = 12; // Retro pixel frame rate (12fps)
[SerializeField] private int resolution = 64; // Per-frame resolution (64x64)
[SerializeField] private int directionCount = 8; // 8 directions
[MenuItem("Tools/LYSC/3D to 2D Sprite Baker")]
public static void ShowWindow()
{
GetWindow<SpriteSheetBakerWindow>("Sprite Baker");
}
private void OnGUI()
{
GUILayout.Label("3D Model -> 2D Pixel Sprite Sheet Baker", EditorStyles.boldLabel);
targetModel = (GameObject)EditorGUILayout.ObjectField("3D Model Prefab", targetModel, typeof(GameObject), true);
clipToBake = (AnimationClip)EditorGUILayout.ObjectField("Animation Clip", clipToBake, typeof(AnimationClip), false);
frameRate = EditorGUILayout.IntSlider("Baking FPS", frameRate, 6, 24);
resolution = EditorGUILayout.IntField("Sprite Resolution (px)", resolution);
directionCount = EditorGUILayout.IntPopup("Direction Count", directionCount, new[] { "1 Direction", "4 Directions", "8 Directions" }, new[] { 1, 4, 8 });
if (GUILayout.Button("Start Sprite Sheet Baking", GUILayout.Height(35)))
{
BakeSpriteSheet();
}
}
private void BakeSpriteSheet()
{
if (targetModel == null || clipToBake == null)
{
EditorUtility.DisplayDialog("Error", "Both a target model and an animation clip must be assigned.", "OK");
return;
}
int totalFrames = Mathf.CeilToInt(clipToBake.length * frameRate);
int sheetWidth = totalFrames * resolution;
int sheetHeight = directionCount * resolution;
Texture2D sheet = new Texture2D(sheetWidth, sheetHeight, TextureFormat.RGBA32, false);
// Configure temporary capture camera and RenderTexture
GameObject camObj = new GameObject("TempBakeCamera");
Camera bakeCam = camObj.AddComponent<Camera>();
bakeCam.orthographic = true;
bakeCam.orthographicSize = 1.0f;
bakeCam.clearFlags = CameraClearFlags.SolidColor;
bakeCam.backgroundColor = new Color(0, 0, 0, 0);
RenderTexture rt = new RenderTexture(resolution, resolution, 24, RenderTextureFormat.ARGB32)
{
filterMode = FilterMode.Point
};
bakeCam.targetTexture = rt;
// Sample across directions and frames
for (int dir = 0; dir < directionCount; dir++)
{
float angle = dir * (360f / directionCount);
targetModel.transform.rotation = Quaternion.Euler(0f, angle, 0f);
for (int f = 0; f < totalFrames; f++)
{
float time = (float)f / frameRate;
clipToBake.SampleAnimation(targetModel, time);
// Render camera
bakeCam.Render();
// Copy pixels
RenderTexture.active = rt;
Texture2D tempFrame = new Texture2D(resolution, resolution, TextureFormat.RGBA32, false);
tempFrame.ReadPixels(new Rect(0, 0, resolution, resolution), 0, 0);
tempFrame.Apply();
// Copy into sheet (row: direction, column: frame)
int startX = f * resolution;
int startY = (directionCount - 1 - dir) * resolution;
sheet.SetPixels(startX, startY, resolution, resolution, tempFrame.GetPixels());
}
}
sheet.Apply();
// Save PNG file
byte[] bytes = sheet.EncodeToPNG();
string path = Path.Combine(Application.dataPath, $"{targetModel.name}_{clipToBake.name}_Sheet.png");
File.WriteAllBytes(path, bytes);
AssetDatabase.Refresh();
// Clean up
bakeCam.targetTexture = null;
RenderTexture.active = null;
DestroyImmediate(camObj);
rt.Release();
EditorUtility.DisplayDialog("Complete", $"Sprite sheet generated at:
{path}", "OK");
}
}
#endif
2. 베이킹 파이프라인의 이점2. Benefits of the Baking Pipeline
- 12fps 도트 애니메이션 느낌 재현: 3D 모션의 60fps 움직임을 12fps로 샘플링하여 레트로 도트 특유의 프레임 타이밍을 재현합니다.
- 드로우콜 및 연산 비용 절감: 3D 스킨드 메시(Skinned Mesh) 렌더러의 본 연산과 드로우콜을 평면 2D 스프라이트 렌더러로 대체하여 다수의 캐릭터를 동시에 렌더링할 수 있습니다.
- Reproducing 12fps Pixel Animation Timing: Sampling 60fps 3D motion at 12fps reproduces the stepped frame cadence characteristic of retro pixel art.
- Reducing Draw Calls and Skinning Overhead: Replacing
SkinnedMeshRendererbone calculations and draw calls with flat 2DSpriteRenderercomponents allows many characters to be rendered simultaneously.
3D 애니메이션 에셋을 2D 스프라이트 시트로 변환하는 자동화 툴을 구축하면, 3D 리깅의 재사용성과 2D 렌더링의 가벼운 런타임 성능을 함께 활용할 수 있습니다.
Building an automated tool that converts 3D animations into 2D sprite sheets lets you combine the reusability of 3D rigging with the lightweight runtime performance of 2D rendering.