XNA, как выбрать плитки с помощью мыши - PullRequest
1 голос
/ 27 марта 2012
public void Draw(SpriteBatch spriteBatch)
    {
        for(int x = 0; x < 10; x++) 
        {
            for (int y = 0; y < 10; y++)
            {
                spriteBatch.Draw(tiles[index[x, y]], tileRect = new Rectangle(x * tileWidth, y * tileHeight, tileWidth, tileHeight), 
                                 Color.White);
            }
        }
    }

У меня есть механизм случайных плиток, и мне интересно, как я могу сделать так, чтобы плитки имели текстуру черного квадрата вокруг нее, и ее можно было выбрать, нажав на нее. и как я могу изменить эту текстуру плитки, когда я нажимаю на нее.

Ответы [ 2 ]

2 голосов
/ 28 марта 2012

Поскольку вы храните плитки в массиве, вы можете использовать что-то вроде этого:

        MouseState ms = Mouse.GetState(); 

        if (ms.LeftButton == ButtonState.Pressed)
        {
            int x = Convert.ToInt32(ms.X) /16;
            int y = Convert.ToInt32(ms.Y) /16 +1;

            tiles[x, y] = //Left button Clicked, Change Texture here!

        }
        if (ms.RightButton == ButtonState.Pressed)
        {
            int x = Convert.ToInt32(ms.X) / 16;
            int y = Convert.ToInt32(ms.Y) / 16 + 1;

            tiles[x, y] = //Right button Clicked, Change Texture here!


        }

/ 16 - для размера плиток в пикселях, и по какой-то причине в моей игре ядобавьте +1 к значению y, для вас это может быть не так.

Для добавления черной текстуры вы можете создать ее на ходу или загрузить в LoadContent ()

и затем нарисуйте его как;

if (tiles[x,y].HasBlackTexture = true)
     spriteBatch.Draw(blah,Color.Black)
0 голосов
/ 28 марта 2012
I am wondering how I could make the tiles have a black square texture around it.
and selectable by clicking on them. 
and how I could change that tile texture when I click on it.

вам понадобится:

отдельная чёрная квадратная «плитка», которую вы рисуете сверху при желании.Пример:

private Texture2D mBlackTile;
...
public void LoadContent()
{
   ...
   mBlackTile = ContentManager.Load<Texture2D>("blackTile");
   ...
}

ссылка на выбранную плитку (координату), которая будет использоваться, чтобы вы знали, где нарисовать плитку черного квадрата.Пример:

private Vector2 mSelectedTileCoordinate = new Vector2();

для обработки щелчка мыши.Пример:

public void Update(GameTime pGameTime)
{
   ...
   MouseState mouseState = Mouse.GetState();
   Vector2 mousePosition = new Vector2(mouseState.X, mouseState.Y);

   if (mouseState.LeftButton == ButtonState.Pressed)
      DoMouseClick(mousePosition);
   ...
}

для преобразования нажатой экранной координаты в координату элемента карты.Пример:

public void DoMouseClick(Vector2 pMouseXY)
{
   ...
   Vector2 tileXY = ScreenToTile(pMouseXY);
   ...
}

private Vector2 ScreenToTile(Vector2 pScreenXY)
{
   // you need to get the position of the map here
   // ex: if the 'camera' is looking at (100, 100), then the map is drawn to (-100, -100)
   Vector2 mapOffset = GetMapOffset();

   // you may need to add or subtract depending what value you are using
   // if mapOffset is the coordinate you are 'looking at', add
   // if mapOffset is the coordinate that the map is being drawn to, subtract
   Vector2 mapXY = pScreenXY +/- mapOffset;

   // you need to get the width and height of the tiles
   Vector2 tileSize = GetTileSize();

   // this should now be the tile coordinate
   // you may or may not want to have rounded the XY values as well
   Vector2 tileXY = mapXY / tileSize;
   return new Vector2((int)tileXY.X, (int)tileXY.Y);
}

, чтобы изменить выбранную плитку на основе нажатой координаты.Пример:

public void DoMouseClick(Vector2 pMouseXY)
{
   ...
   Vector2 tileXY = ScreenToTile(pMouseXY);

   mSelectedTileCoordinate = tileXY;
}

и нарисовать плитку в вашем коде розыгрыша.Пример:

public void Draw(SpriteBatch spriteBatch)
{
    for(int x = 0; x < 10; x++) 
    {
        for (int y = 0; y < 10; y++)
        {
            spriteBatch.Draw(tiles[index[x, y]], tileRect = new Rectangle(x * tileWidth, y * tileHeight, tileWidth, tileHeight), 
                             Color.White);
        }
    }

    // draw selection
    Vector2 screenXY = TileToScreen(mSelectedTileCoordinate);
    Rectangle drawArea = new Rectangle(screenXY.X, screenXY.Y, tileWidth, tileHeight);
    spriteBatch.Draw(mBlackTile, drawArea, Color.White);
}

private Vector2 TileToScreen(Vector2 pTileXY)
{
   // this does the reverse of ScreenToTile

   Vector2 tileSize = GetTileSize();
   Vector2 mapXY = pTileXY * tileSize;       

   Vector2 mapOffset = GetMapOffset();

   // you'll have to do this the opposite way from ScreenToTile()
   Vector2 screenXY = mapXY +/- mapOffset;       

   return screenXY;
}
...