0
\$\begingroup\$

I'm currently designing a 2D game engine in C#, just had a quick question.

I have a SpriteSheet class that splits up a sprite into several different sprites (like a tileset for a example) and stores them in a list. Which is great, because now I can access sprites via it's corresponding index in the sheet.

However, I would really like to add a feature that will let me access a sprite by specifying the row and column it resides in (in the original sprite). I just don't know the equation to find where the sprite is in the list.

Here is what I have so far:

    public Sprite this[int index]
    {
        get { return this.sprites[index]; }
    }

    public Sprite this[int row, int column]
    {
        get
        {
            // Get the width and height of each individual sprite in the sheet.
            int cellWidth = this[0].Width;
            int cellHeight = this[0].Height;

            // Figure out and how many rows and columns are in the entire sprite sheet
            int rows = this.sprite.Width / cellWidth;
            int columns = this.sprite.Height / cellHeight;

            // Here is where I want to return the sprite located at the row and column specified.
            return this.sprites[ /* what do i put in here? */ ];
        }
    }

Also, I don't know if it will help but here is the method I use to fill the list with sprites:

    private void CreateSheet(Sprite sprite, int xOffset, int yOffset)
    {
        for (int y = 0; y < sprite.Height; y += yOffset)
        {
            for (int x = 0; x < sprite.Width; x += xOffset)
            {
                this.sprites.Add(sprite.Clone(new Rectangle(x, y, xOffset, yOffset)));
            }
        }
    }
\$\endgroup\$

2 Answers 2

0
\$\begingroup\$

Since you are scanning from left to right and then top to bottom, you move one row down by adding (number of columns per row).

return this.sprites[row*columns + column];

meaning you don't need

int cellHeight = this[0].Height;
...
int columns = this.sprite.Height / cellHeight;
\$\endgroup\$
0
\$\begingroup\$

After getting extremely frustrated for the past hour I've stumbled upon a few questions on stack overflow that talk about converting 1D arrays to 2D arrays.

Finally, I was able to understand what to do, and my solution is this:

    public Sprite this[int row, int column]
    {
        get { return this[row + (this.sprite.Width / this[0].Height) * column]; }
    }
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .