Search code examples
c#selectxnamousetile

XNA how to select tiles with mouse


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);
            }
        }
    }

I have a random tile engine and 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.


Solution

  • Since your storing the tiles in an array, You can use something like this to do it:

            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 is for the tiles size in pixels, and for some reason in my game I have to add +1 to the y value, for you it might not be the case.

    For adding a Black Texture, You can either create one on the go, Or load it in LoadContent()

    and then draw it like;

    if (tiles[x,y].HasBlackTexture = true)
         spriteBatch.Draw(blah,Color.Black)