private Vector2 SnapToGrid(Vector2 position, Rectangle gridArea, float zoom, Vector2 gridSize, float tolerance) { gridSize *= zoom; if (gridSize.X < 1.0f) { return(position); } if (gridSize.Y < 1.0f) { return(position); } Vector2 snappedPos = position; snappedPos.X -= gridArea.X; snappedPos.Y -= gridArea.Y; Vector2 gridPos = new Vector2( MathUtils.RoundTowardsClosest(snappedPos.X, gridSize.X), MathUtils.RoundTowardsClosest(snappedPos.Y, gridSize.Y)); if (Math.Abs(gridPos.X - snappedPos.X) < tolerance) { snappedPos.X = gridPos.X; } if (Math.Abs(gridPos.Y - snappedPos.Y) < tolerance) { snappedPos.Y = gridPos.Y; } snappedPos.X += gridArea.X; snappedPos.Y += gridArea.Y; return(snappedPos); }
public static void DrawGrid(SpriteBatch spriteBatch, int gridCells, Vector2 gridCenter, Vector2 roundedGridCenter, float alpha = 1.0f) { var horizontalLine = GUI.Style.GetComponentStyle("HorizontalLine").GetDefaultSprite(); var verticalLine = GUI.Style.GetComponentStyle("VerticalLine").GetDefaultSprite(); Vector2 topLeft = roundedGridCenter - Vector2.One * GridSize * gridCells / 2; Vector2 bottomRight = roundedGridCenter + Vector2.One * GridSize * gridCells / 2; for (int i = 0; i < gridCells; i++) { float distFromGridX = (MathUtils.RoundTowardsClosest(gridCenter.X, GridSize.X) - gridCenter.X) / GridSize.X; float distFromGridY = (MathUtils.RoundTowardsClosest(gridCenter.X, GridSize.Y) - gridCenter.X) / GridSize.Y; float normalizedDistX = Math.Abs(i + distFromGridX - gridCells / 2) / (gridCells / 2); float normalizedDistY = Math.Abs(i - distFromGridY - gridCells / 2) / (gridCells / 2); float expandX = MathHelper.Lerp(30.0f, 0.0f, normalizedDistX); float expandY = MathHelper.Lerp(30.0f, 0.0f, normalizedDistY); GUI.DrawLine(spriteBatch, horizontalLine, new Vector2(topLeft.X - expandX, -bottomRight.Y + i * GridSize.Y), new Vector2(bottomRight.X + expandX, -bottomRight.Y + i * GridSize.Y), Color.White * (1.0f - normalizedDistY) * alpha, depth: 0.6f, width: 3); GUI.DrawLine(spriteBatch, verticalLine, new Vector2(topLeft.X + i * GridSize.X, -topLeft.Y + expandY), new Vector2(topLeft.X + i * GridSize.X, -bottomRight.Y - expandY), Color.White * (1.0f - normalizedDistX) * alpha, depth: 0.6f, width: 3); } }