所以我被困在如何能够将monogame/XNA中的鼠标位置转换为我的网格位置。我试图实现的基本上是当我单击它们时,将网格中特定单元格上的矩形的颜色更改为不同的颜色。获取鼠标在网格上的位置
这是我第一次在网格系统上工作,并且我没有真正了解如何做到这一点。
这是我建立我的网格。这里基本上发生的是我首先用0填充网格中的每个单元格。根据我在Game1类的update方法中分配的值,矩形的颜色将会改变。
谢谢!
public int[,] gridCell;
Texture2D texture;
public Rectangle rect;
int col;
int row;
const int gridSize = 32;
//Initializes the constructor
public Grid(int sizeCol, int sizeRow)
{
//texture = sprite;
col = sizeCol;
row = sizeRow;
gridCell = new int[col, row];
for(int i = 0; i<col;i++)
{
for(int j = 0; j<row;j++)
{
gridCell[i, j] = 0;
}
}
}
public void Draw(SpriteBatch spritebatch)
{
for (int i = 0; i <= col-1; i++)
{
for (int j = 0; j <= row-1; j++)
{
if (gridCell[i, j] == 0)
{
spritebatch.FillRectangle(i * 32, j * 32, 31, 31, Color.CornflowerBlue, 0f);
spritebatch.DrawRectangle(new Vector2(i * 32, j * 32), new Vector2(32, 32), Color.Black, 1f);
}
else if(gridCell[i,j] == 1)
{
spritebatch.FillRectangle(i * 32, j * 32, 31, 31, Color.Yellow, 0f);
spritebatch.DrawRectangle(new Vector2(i * 32, j * 32), new Vector2(32, 32), Color.Black, 1f);
}
else if (gridCell[i, j] == 2)
{
spritebatch.FillRectangle(i * 32, j * 32, 31, 31, Color.Red, 0f);
spritebatch.DrawRectangle(new Vector2(i * 32, j * 32), new Vector2(32, 32), Color.Black, 1f);
}
else if (gridCell[i, j] == 3)
{
spritebatch.FillRectangle(i * 32, j * 32, 31, 31, Color.Purple, 0f);
spritebatch.DrawRectangle(new Vector2(i * 32, j * 32), new Vector2(32, 32), Color.Black, 1f);
}
else if (gridCell[i, j] == 4)
{
spritebatch.FillRectangle(i * 32, j * 32, 31, 31, Color.Blue, 0f);
spritebatch.DrawRectangle(new Vector2(i * 32, j * 32), new Vector2(32, 32), Color.Black, 1f);
}
else if (gridCell[i, j] == 5)
{
spritebatch.FillRectangle(i * 32, j * 32, 31, 31, Color.Black, 0f);
spritebatch.DrawRectangle(new Vector2(i * 32, j * 32), new Vector2(32, 32), Color.Black, 1f);
}
}
}
}
我不是太熟悉MonoGame,但你可能需要将鼠标光标的位置转换成游戏世界(网格)坐标系,这与其他游戏引擎相当常见,所以请牢记这一点。您需要测试鼠标位置是否在网格单元矩形中。为此,请查看[Rectangle.Contains方法](https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.rectangle.contains.aspx)。然后,您可以对照您的网格单元测试鼠标的X/Y坐标。 –
“更改网格中特定单元格上的矩形的颜色”但您只有1个矩形用于整个网格单元格?为什么不为每个单元格分配一个矩形并绘制这些矩形? – LibertyLocked