Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I'm trying to get a sprite sheet clipped in the right order but I'm a bit stumped, every iteration I've tried has tended to be in the wrong order. This is my current implementation.

    Frames = (TempSurface->h / ClipHeight) * (TempSurface->w / ClipWidth);
    SDL_Rect Clips[Frames];
    for (i = 0; i < Frames; i++) {
            if (i != 0 && i % (TempSurface->h / ClipHeight) == 0)
                    ColumnIndex++;
            Clips[i].x = ColumnIndex * ClipWidth;
            Clips[i].y = i % (TempSurface->h / ClipHeight) * ClipHeight;
            Clips[i].w = ClipWidth;
            Clips[i].h = ClipHeight;
    }

Where TempSurface is the entire sheet loaded to a SDL_Surface and Clips[] is an array of SDL_Rects. What results from this is a sprite sheet set to SDL_Rects in the wrong order.

For example I need a sheet of dimensions 4x4 to look like this:

| 0 | 1 | 2 | 3 |
| 4 | 5 | 6 | 7 |
| 8 | 9 | 10| 11|
| 12| 13| 14| 15|

But instead I get this order:

| 0 | 4 | 8 | 12|
| 1 | 5 | 9 | 13|
| 2 | 6 | 10| 14|
| 3 | 7 | 11| 15|

Columns and rows order does not match. What should I do to fix the order?

share|improve this question

1 Answer 1

up vote 4 down vote accepted

You just swap your rows/columns ordering. Iterating from 0 to Frames-1, you first increase X and every time you hit the spritesheets width - increase Y and reset X.

The code should be looking like so:

for (i = 0; i < Frames; i++) {
    // Increase the row once every time horizontal range is done
    if (i != 0 && i % (TempSurface->w / ClipWidth) == 0)
        RowIndex++;

    Clips[i].x = i % (TempSurface->w / ClipWidth) * ClipWidth;
    Clips[i].y = RowIndex * ClipHeight;
    Clips[i].w = ClipWidth;
    Clips[i].h = ClipHeight;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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