Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- /// <summary>
- /// Templated 2D grid class.
- /// </summary>
- /// <typeparam name="T">Grid data type</typeparam>
- public class Grid<T>
- {
- /// <summary>
- /// Holds the grid data.
- /// </summary>
- T[] data;
- /// <summary>
- /// Size of the grid.
- /// </summary>
- public Vector2Int Size { get; private set; }
- /// <summary>
- /// Grid offset.
- /// </summary>
- public Vector2Int Offset { get; set; }
- /// <summary>
- /// Default constructor.
- /// </summary>
- /// <param name="size">Size of the grid</param>
- /// <param name="offset">Offset of the grid</param>
- public Grid(Vector2Int size, Vector2Int offset)
- {
- Size = size;
- Offset = offset;
- data = new T[size.x * size.y];
- }
- /// <summary>
- /// Get index of grid data based on 2D position.
- /// </summary>
- /// <param name="position">2D position to get index of</param>
- /// <returns>Index of grid data</returns>
- public int GetIndex(Vector2Int position)
- {
- return position.x + position.y * Size.x;
- }
- /// <summary>
- /// Is the given position inside the grid?
- /// </summary>
- /// <param name="position">2D position to check</param>
- /// <returns>True when inside the grid, false otherwise</returns>
- public bool IsInside(Vector2Int position)
- {
- return position.x >= 0 && position.x < Size.x && position.y >= 0 && position.y < Size.y;
- }
- /// <summary>
- /// Get data at the given position (with x and y coordinates).
- /// </summary>
- /// <param name="x">X coordinate</param>
- /// <param name="y">Y coordinate</param>
- /// <returns>Value at the given position</returns>
- public T this[int x, int y]
- {
- get
- {
- return this[new Vector2Int(x, y)];
- }
- set
- {
- this[new Vector2Int(x, y)] = value;
- }
- }
- /// <summary>
- /// Get data at the given position (with Vector2Int).
- /// </summary>
- /// <param name="position">Position to get data of</param>
- /// <returns>Value at the given position</returns>
- public T this[Vector2Int position]
- {
- get
- {
- position += Offset;
- return data[GetIndex(position)];
- }
- set
- {
- position += Offset;
- data[GetIndex(position)] = value;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement