본문 바로가기
개발/Unity

Unity) 2D Grid 만들기 ( 2D Grid )

by 테샤르 2025. 2. 4.

 2D Grid 만들기 ( 2D Grid )

 

몬스터의 크기나 특정 위치를 확인하기 위해서 격자를 처리하는 코드를 작업했다.

단순히 나열하는것보다는 전체적인 크기를 가늠할때도 유용하게 사용이 가능하다.

 

반응형

 

< 2D 격자 만들기 >



< Insepctor >

인스펙터에서 격자를 쉽게 사용하기 위해서

격자 사이즈 / 격자 개수 / 격자의 Offset / 격자 Color 를 설정이 가능하게 작업했다.

 

반응형

 

< Script >

using UnityEditor;
using UnityEngine;

/// <summary>
/// 2D 격자 그리기
/// </summary>
public class DrawGrid : MonoBehaviour
{
	[SerializeField]
	private float gridSize = 1.0f;
	[SerializeField]
	private int divisions = 10;
	[SerializeField]
	private Vector2 offset= Vector2.zero;

	[SerializeField]
	private Color gridColor = Color.green;

	private void OnDrawGizmos()
	{
		// Ensure the gridSize is greater than 0 to avoid errors
		if (gridSize <= 0 || divisions <= 0)
		{
			Debug.LogWarning("Grid size and divisions must be greater than zero.");
			return;
		}

		// Draw the grid
		DrawHeightGrid();
	}

	private void DrawHeightGrid()
	{
		// Store the color to revert after drawing
		Handles.color = gridColor;

		// Loop for vertical and horizontal lines
		for (int i = 0; i <= divisions; i++)
		{
			float t = i / (float)divisions; // Calculate the normalized value (0 to 1)
			float height = t * gridSize; // Scale it to the grid size

			// Draw horizontal lines (X-axis)
			Handles.DrawLine(
				new Vector3(offset.x, offset.y + height, 0), // Start point
				new Vector3(offset.x + gridSize, offset.y +height, 0) // End point
			);

			// Draw vertical lines (Y-axis)
			Handles.DrawLine(
				new Vector3(offset.x + height, offset.y, 0), // Start point
				new Vector3(offset.x + height, offset.y + gridSize, 0) // End point
			);
		}

		// Revert Handles color to white
		Handles.color = Color.white;
	}
}

 

 

 

★★☆☆☆

 

반응형

댓글