For my videogame in C – SDL I need to use a spritesheet I made myself.
The picture size is 100×100 and each picture I want to take is 25×25
I found somewhere a nice function which can do that for me:
// Wraps a rectangle around every sprite in a sprite sheet and stores it in an array of rectangles(Clip[])
void spriteSheet(){
int SpriteWidth = 25; int SpriteHeight= 25; int SheetDimension = 4;
int LeSprites = SheetDimension * SheetDimension;// Number of Sprites on sheet
SDL_Rect Clip[LeSprites]; // Rectangles that will wrap around each sprite
int SpriteXNum = 0;// The number sprite going from left to right
int SpriteYNum = 0;// The number sprite going from top to bottom
int YIncrement = 0;// Increment for each row.
int i = 0;
for(i = 0; i< LeSprites; i++){// While i is less than number of sprites
if(i = 0){// First sprite starts at 0,0
Clip[i].x = 0;
Clip[i].y = 0;
Clip[i].w = SpriteWidth;
Clip[i].h = SpriteHeight;
}
else{
if(SpriteXNum < SheetDimension - 1 ){// If we have reached the end of the row, go back to the front of the next row
SpriteXNum = 0;
}
if(YIncrement < SheetDimension - 1){
SpriteYNum += 1; // Example of 4X4 Sheet
} // ________________
Clip[i].x = SpriteWidth * SpriteXNum; // | 0 | 1 | 2 | 3 |
Clip[i].y = SpriteHeight * SpriteYNum; // |===============|
// | 0 | 1 | 2 | 3 |
// |===============|
Clip[i].w = SpriteWidth; // | 0 | 1 | 2 | 3 |
Clip[i].h = SpriteHeight; // |===============|
// | 0 | 1 | 2 | 3 |
} // |---------------|
SpriteXNum++;
YIncrement++;
}
}
But now I dont know how can I load my (png) picture on it to apply this function.
It looks like this piece of code just gives you the clipping coordinates for each individual square of the sprite sheet. It doesn’t seem to interact with the image at all.
If you want to load PNG you should use the additional SDL_image library. It will produce an
SDL_Surfacepointer which you can use with the clipping coordinates when you callSDL_BlitSurfaceto draw it to the screen.Note that you should try to get the
SpriteDimension, etc values from the image itself (by dividing the image width (w) and height (h) by the size of an individual sprite).In the future, you could extend this idea by devising a SpriteSheet class which holds its calculated clipping positions and other information about the sprite sheet and which wraps the call to
SDL_BlitSurfaceas appropriate.