Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- public class GridManager : MonoBehaviour
- {
- public static GridManager Instance; // Singleton for easy access
- public int width = 10, height = 10; // Define grid size
- public float cellSize = 1.0f; // Size of each grid cell
- private Transform[,] gridArray; // 2D array for grid storage
- public Vector2 gridOrigin = Vector2.zero; // Adjust this in Unity Inspector
- private void Awake()
- {
- if (Instance == null)
- Instance = this;
- else
- Destroy(gameObject);
- gridArray = new Transform[width, height]; // Initialize grid array
- Debug.Log("GridManager Loaded. Grid Size: " + width + "x" + height);
- }
- void OnDrawGizmos()
- {
- Gizmos.color = Color.green; // Grid color
- for (int x = 0; x < width; x++)
- {
- for (int y = 0; y < height; y++)
- {
- Vector2 cellPosition = new Vector2(x * cellSize, y * cellSize) + gridOrigin;
- Gizmos.DrawWireCube(cellPosition, Vector2.one * (cellSize * 0.9f));
- }
- }
- }
- // Converts world position to the nearest grid cell position
- public Vector2 SnapToGrid(Vector2 worldPosition)
- {
- Debug.Log($"World Position: {worldPosition}");
- float relativeX = worldPosition.x - gridOrigin.x;
- float relativeY = worldPosition.y - gridOrigin.y;
- Debug.Log($"Relative Position (after subtracting origin): {new Vector2(relativeX, relativeY)}");
- int x = Mathf.RoundToInt(relativeX / cellSize);
- int y = Mathf.RoundToInt(relativeY / cellSize);
- Debug.Log($"Snapped Grid Coordinates: ({x}, {y})");
- Vector2 snappedPosition = new Vector2(x * cellSize + gridOrigin.x, y * cellSize + gridOrigin.y);
- Debug.Log($"Final Snapped Position: {snappedPosition}");
- return snappedPosition;
- }
- // Check if a grid cell is empty
- public bool IsCellEmpty(Vector2 worldPosition)
- {
- int x = Mathf.RoundToInt(worldPosition.x / cellSize);
- int y = Mathf.RoundToInt(worldPosition.y / cellSize);
- if (x >= 0 && x < width && y >= 0 && y < height)
- return gridArray[x, y] == null; // True if empty
- return false; // Out of bounds
- }
- // Place block on the grid and log its position
- public void PlaceBlock(Vector2 worldPosition, Transform block)
- {
- int x = Mathf.RoundToInt(worldPosition.x / cellSize);
- int y = Mathf.RoundToInt(worldPosition.y / cellSize);
- if (x < 0 || x >= width || y < 0 || y >= height)
- {
- Debug.LogWarning($"Out of Bounds! Tried to place block at ({x}, {y})");
- return;
- }
- if (gridArray[x, y] == null)
- {
- gridArray[x, y] = block;
- Debug.Log($"✅ Block locked at Grid Position ({x}, {y})");
- }
- else
- {
- Debug.LogWarning($"⚠️ Cell ({x}, {y}) is already occupied!");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement