0
\$\begingroup\$

Let's say I have a tile sheet that contains 8 sprites per sheet. Each sprite is a tile of 30x30.

I wrote my own custom map parser/map loader however I'm having trouble extracting a certain tile sprite from the file. I'll describe my problem better in order for everyone to understand.

I wrote an enum of materials, each material has a value according to it's location relative to the tile sheet. For example void is 1, grass is 2, rock is 3, etc. So in my tile sheet they are represented as such:

+---+---+---+---+---+
| 1 | 2 | 3 | 4 | 5 |
+---+---+---+---+---+

Which is equivalent to:

+------+-------+-------+
| void | grass | stone |
+------+-------+-------+

Basically when rendering, I created a tile class, each tile has 2 coordinates: X and Y (They are calculated automatically) and a material which can be represented either as a number, either as a value (ID). When rendering, I have a vector of sprites which are all taken from 1 file called tilesheet.png, however each of them must only draw a certain portion of the tile sheet, for example say I have something like this:

tile coordinateBounds(topLeftX, topLeftY, tileWidth, tileHeight); 

During the initialization of the map I calculate an array of tiles, and I give each of them their position, their materials based on the values in a map file and a few other variables such as collision. I need to apply the coordinateBounds to each of them according to their material value. For example if the material is grass it should only take the grass sprite from the tilesheet. I must also mention I'm using SFML, and there are no borders or spacing between the tiles.

\$\endgroup\$
1
\$\begingroup\$

You want to draw the portion of the tile sheet representing the desired material. In SFML 1.6, this can be done by creating a clipping region with a sf::IntRect.

sf::Sprite tileSheet;
sf::IntRect clipping;
int frame = 0;              //id of the material you want to draw
int columns = 5;            //number of columns in the tile sheet
int frameWidth = 30;
int frameHeight = 30;

//set the clipping rectangle
clipping.Left = (frame % columns) * frameWidth;
clipping.Top = (frame / columns) * frameHeight;
clipping.Right = clipping.Left + frameWidth;
clipping.Bottom = clipping.Top + frameHeight;

//apply the clipping rectangle to the tile sheet so it knows what portion to draw
tileSheet.SetSubRect(clipping);
\$\endgroup\$
  • \$\begingroup\$ Thanks a ton, this is exactly what I've been looking for. \$\endgroup\$ – Bugster Dec 15 '12 at 11:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.