using Godot; using System; using System.Collections.Generic; using System.Linq; public partial class GridMap2D : Node2D { public int _cellSize = 16; public Vector2 _sizeInPixels, _sizeInCells; public Area2D _playArea; public GridMarker _gridMarker; public List _leftEdges = new(), _rightEdges = new(); public List> _gridMarkers = new(); public override void _Ready() { base._Ready(); _playArea = GetNode("PlayArea"); StaticBody2D firstOnLeft = GetNode("LeftEdge1"); StaticBody2D firstOnRight = GetNode("RightEdge1"); _leftEdges.Add(firstOnLeft); _rightEdges.Add(firstOnRight); CollisionShape2D firstOnLeftBounds = firstOnLeft.GetNode("Bounds"); CollisionShape2D firstOnRightBounds = firstOnRight.GetNode("Bounds"); _gridMarker = GetNode("GridMarker"); CollisionShape2D playAreaBounds = _playArea.GetNode("Bounds"); _sizeInPixels = new Vector2((int)playAreaBounds.Shape.GetRect().Size.X, (int)playAreaBounds.Shape.GetRect().Size.Y); _sizeInCells = new Vector2(_sizeInPixels.X / _cellSize, _sizeInPixels.Y / _cellSize); for (int i = 0; i < _sizeInCells.Y; i++) { _gridMarkers.Add([]); for (int j = 0; j < _sizeInCells.X; j++) { GridMarker newGridMarker = (GridMarker)_gridMarker.Duplicate(); newGridMarker._address = new Vector2I(j, i); newGridMarker.Position = new Vector2(_playArea.Position.X - playAreaBounds.Shape.GetRect().Size.X / 2 + (j+.5f)*_cellSize, _playArea.Position.Y - playAreaBounds.Shape.GetRect().Size.Y / 2 + (i+.5f)*_cellSize); _gridMarkers[i].Add(newGridMarker); AddChild(newGridMarker); } } int leftEdgeSectionSizeY = (int)firstOnLeftBounds.Shape.GetRect().Size.Y, rightEdgeSectionSizeY = (int)firstOnRightBounds.Shape.GetRect().Size.Y; int leftEdgeSectionsCount = (int)_sizeInPixels.Y / leftEdgeSectionSizeY, rightEdgeSectionsCount = (int)_sizeInPixels.Y / rightEdgeSectionSizeY; for (int i = 1; i < leftEdgeSectionsCount; i++) { StaticBody2D newLeftSection = (StaticBody2D)firstOnLeft.Duplicate(); newLeftSection.Position += new Vector2(0, leftEdgeSectionSizeY * i); _leftEdges.Add(newLeftSection); AddChild(newLeftSection); } for (int i = 1; i < rightEdgeSectionsCount; i++) { StaticBody2D newRightSection = (StaticBody2D)firstOnRight.Duplicate(); newRightSection.Position += new Vector2(0, rightEdgeSectionSizeY * i); _rightEdges.Add(newRightSection); AddChild(newRightSection); } _gridMarker.QueueFree(); } public GridMarker GetMarkerByAddress(Vector2I COORDINATES) { return _gridMarkers[COORDINATES.Y][COORDINATES.X]; } public GridMarker GetMarkerFromOffset(GridMarker GRID_MARKER, Vector2I STEP) { return _gridMarkers[GRID_MARKER._address.Y + STEP.Y][GRID_MARKER._address.X + STEP.X]; } public List GetMarkerInRange(GridMarker GRID_MARKER, int RANGE) { return [.. _gridMarkers.SelectMany(m => m).Where(m => (GRID_MARKER._address - m._address).Length() <= RANGE).Cast()]; } }