Corey
Corey

Reputation: 73

Selection texture on tiles causing performance issues

public void Draw(SpriteBatch spriteBatch)
    {
        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                Vector2 mouseCoord = GetMouseTilePosition();
                if (mouseCoord.X > 0)
                {
                    spriteBatch.Draw(selection, tileRect = new Rectangle((int)mouseCoord.X * 64, (int)mouseCoord.Y * 64, 64, 64),
                                    Color.White);
                }
                spriteBatch.Draw(tiles[index[x,y]].texture, tileRect = new Rectangle(x * 64, y * 64, 64, 64), 
                    Color.White);          
            }
        }  
    }

    public Vector2 GetMouseTilePosition()
    {
        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                if (IsMouseInsideTile(x, y))
                {
                    return new Vector2(x, y);
                }
            }
        }

        return new Vector2(-1, -1);
    }

    public bool IsMouseInsideTile(int x, int y)
    {
        MouseState MS = Mouse.GetState();
        return (MS.X >= x * 64 && MS.X <= (x + 1) * 64 &&
            MS.Y >= y * 64 && MS.Y <= (y + 1) * 64);
    }

It is very cpu intensive. Is there a better way to do this code? Also I have a camera how can I change this to factor that in so I get the actual mouse position

Upvotes: 0

Views: 133

Answers (1)

Msonic
Msonic

Reputation: 1456

Jon Skeet is right, you could directly call IsMouseInsideTile() instead of looping through your array several times. (Currently, you're checking where the mouse is in the whole tile array, for each tile, instead of only checking the current tile you're in).

public void Draw(SpriteBatch spriteBatch)
{
    for (int x = 0; x < width; x++)
    {
        for (int y = 0; y < height; y++)
        {
            if (IsMouseInsideTile(x, y))
            {
                spriteBatch.Draw(selection, tileRect = new Rectangle(x * 64, y * 64, 64, 64),
                                    Color.White);
            }
            spriteBatch.Draw(tiles[index[x,y]].texture, tileRect = new Rectangle(x * 64, y * 64, 64, 64), 
                    Color.White);          
        }
    }  
}

I'm sorry, it's all my fault, I submitted this code quickly earlier without double checking. This new version should improve your performance drastically.

Upvotes: 1

Related Questions