so I am working on a game, following a tutorial online. Currently I have some FPS built into the system, and a simple animation which uses pieces of a sprite like such:
if( frameCount > 12 )
frameCount = 0;
//hero frames
SDL_Rect clip[ 13 ];
clip[ 0 ].x = 0;
clip[ 0 ].y = 0;
clip[ 0 ].w = 44;
clip[ 0 ].h = 39;
clip[ 1 ].x = 51;
clip[ 1 ].y = 0;
clip[ 1 ].w = 44;
clip[ 1 ].h = 39;
clip[ 2 ].x = 102;
clip[ 2 ].y = 0;
clip[ 2 ].w = 44;
clip[ 2 ].h = 39;
...
...
SDL_BlitSurface( hero, &clip[ frameCount ], destination, &offset );
frameCount++;
Now this works just fine, and each iteration of the while loop will cause it to play the next frame in the animation (This animation is part of a character class by the way).
The problem I am facing is the speed of the animation. It takes place at the current FPS of the game, which is 60. I want to be able to control the speed of the player animation separately, so I can slow it down to开发者_JAVA百科 a reasonable speed.
Does anyone have any suggestions on how I could go about doing this?
note: There are 13 frames all together.
You have separate your refresh rate (60 fps) from your animation rate. The best solution, in my opinion, is to tie your animation rate to the real time clock. In SDL, you can do this with the SDL_Ticks() function, which you can use to measure time in millisecond resolution.
As an example, consider this example (not working code, just a sketch):
void init() {
animationRate = 12;
animationLength = 13;
startTime = SDL_Ticks();
}
void drawSprite() {
int frameToDraw = ((SDL_Ticks() - startTime) * animationRate / 1000) % animationLength;
SDL_BlitSurface( hero, &clip[ frameToDraw ], destination, &offset );
}
In case it isn't clear, the frameToDraw
variable is computed by calculating how much time passed since the animation started to play. You multiply that by the animation rate and you get how many absolute frames at the animation rate have passed. You then apply the modulo operator to reduce this number to the range of your animation length and that gives you the frame you need to draw at that time.
If your refresh rate is slower than your animation rate your sprite will skip frames to keep up with the requested animation rate. If the refresh rate is faster then the same frame will be drawn repeatedly until the time to display the next frame comes.
I hope this helps.
What Miguel has written works great. Another method you can use is, to use a timer, set it to fire at a certain frequency and in that frequency, increment your sprite index.
Note that you should always make your rendering and logic separate.
精彩评论