Skip to content

Instantly share code, notes, and snippets.

@skrolikowski
Last active February 5, 2019 07:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skrolikowski/cb379049261619301bc110dc79138a2d to your computer and use it in GitHub Desktop.
Save skrolikowski/cb379049261619301bc110dc79138a2d to your computer and use it in GitHub Desktop.
GameExample.Map.IsoGrid
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using MonoGame.Extended;
using MonoGame.Extended.Shapes;
namespace EGen.Map
{
public class Grid
{
public int Rows { get; }
public int Cols { get; }
public int Size { get; }
public List<Cell> Cells { get; }
public Grid(int rows, int cols, int size)
{
Rows = rows;
Cols = cols;
Size = size;
Cells = new List<Cell>(rows * cols);
for (int r = 0; r < rows; ++r)
for (int c = 0; c < cols; ++c)
Cells.Add(new Cell(this, r, c));
}
public Cell GetCell(int row, int col) => Cells[GetIndex(row, col)];
public int GetIndex(int row, int col)
{
int idx = (col - 1) + (row - 1) * Cols;
if (idx < 0 || idx > Cells.Capacity)
throw new ArgumentException("Invalid " + (row > Rows ? "Row" : "Col") + " Request.");
return idx;
}
}
public class Cell
{
private readonly Grid _grid;
public int Row { get; set; }
public int Col { get; set; }
public int Depth { get; }
public int Index { get => _grid.GetIndex(Row, Col); }
public float Unit { get => Dimensions.Width / 2; }
public float HalfUnit { get => Unit / 2; }
public Vector2 Position { get; set; }
public Size2 Dimensions { get; set; }
public RectangleF Container { get; set; }
public Vector2 IsoPosition { get; }
public List<Polygon> IsoPolygons { get; }
public Cell(Grid grid, int row, int col, int depth = 0)
{
_grid = grid;
Row = row;
Col = col;
Depth = depth;
Dimensions = new Size2(grid.Size, grid.Size);
Position = new Vector2((Row - 1) * Dimensions.Height, (Col - 1) * Dimensions.Width);
Container = new RectangleF(Position, Dimensions);
List<Vector2> indices = new List<Vector2>
{
new Vector2( 0, 0),
new Vector2( Unit, HalfUnit),
new Vector2( 0, Unit),
new Vector2(-Unit, HalfUnit)
};
indices.Add(indices[0].Translate(0, Unit * -Depth));
indices.Add(indices[1].Translate(0, Unit * -Depth));
indices.Add(indices[2].Translate(0, Unit * -Depth));
indices.Add(indices[3].Translate(0, Unit * -Depth));
IsoPosition = new Vector2((Col - Row) * Unit, (Col + Row) * HalfUnit);
IsoPolygons = new List<Polygon>() {
new Polygon(
new List<Vector2>(){
indices[4], indices[5], indices[6], indices[7]
}),
new Polygon(
new List<Vector2>(){
indices[7], indices[6], indices[2], indices[3]
}),
new Polygon(
new List<Vector2>(){
indices[6], indices[5], indices[1], indices[2]
})
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment