【发布时间】:2015-08-16 22:58:08
【问题描述】:
所以我想做一个简单的精灵动画。 我使用这张图片作为精灵:http://answers.unity3d.com/storage/temp/5358-1123_01_01.jpg
这是代码:
#include <SDL.h>
#include <SDL_image.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
//Screen dimension constants
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
#define PATH_TO_IMAGE "sprite.jpg"
int main(int argc, char* args[]) {
const int WALKING_ANIMATION_FRAMES = 8;
SDL_Rect gSpriteClips[ 8 ] = {
(SDL_Rect) {.h = 112, .w = 88, .x = 16, .y = 16},
(SDL_Rect) {.h = 112, .w = 88, .x = 133, .y = 16},
(SDL_Rect) {.h = 112, .w = 88, .x = 265, .y = 16},
(SDL_Rect) {.h = 112, .w = 88, .x = 398, .y = 16},
(SDL_Rect) {.h = 112, .w = 88, .x = 16, .y = 139},
(SDL_Rect) {.h = 112, .w = 88, .x = 132, .y = 139},
(SDL_Rect) {.h = 112, .w = 88, .x = 264, .y = 139},
(SDL_Rect) {.h = 112, .w = 88, .x = 397, .y = 139},
};
//The window renderer
SDL_Renderer *renderer = NULL;
//The window we'll be rendering to
SDL_Window *gWindow;
//Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) == 0) {
//Create window
gWindow = SDL_CreateWindow("Character animation", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (gWindow != NULL) {
//Get window surface
renderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
int imgFlags = IMG_INIT_JPG;
if (IMG_Init(imgFlags) & imgFlags) {
bool quit = false;
SDL_Texture *texture = IMG_LoadTexture(renderer, PATH_TO_IMAGE);
int frame = 0;
int selected_frame = 0;
while (!quit) {
SDL_RenderClear(renderer);
selected_frame = (frame / WALKING_ANIMATION_FRAMES);
SDL_Rect *currentClip = &gSpriteClips[selected_frame];
SDL_RenderCopy(renderer, texture, currentClip, &((SDL_Rect){ .x = 16, .y = 16, .h = 112, .w = 88}) );
SDL_RenderPresent(renderer);
printf("Selected frame: %d -- %d - %d\n", selected_frame, frame, WALKING_ANIMATION_FRAMES);
++frame;
if ((frame / WALKING_ANIMATION_FRAMES) >= WALKING_ANIMATION_FRAMES) {
printf("Entrei aqui\n");
frame = 0;
}
}
}
} else {
printf("SDL_Init failed ON WINDOW: %s\n", SDL_GetError());
}
}
//Destroy window
SDL_DestroyRenderer(renderer);
renderer = NULL;
SDL_DestroyWindow(gWindow);
gWindow = NULL;
//Quit SDL subsystems
IMG_Quit();
SDL_Quit();
return (EXIT_SUCCESS);
}
代码编译没有任何问题。 这是基于 Lazy Foo 第 14 课。
我遇到的问题是在 10 或 15 秒后程序停止响应(窗口变灰,精灵动画停止)。 让我明确一点,动画确实有效,并且在程序冻结之前它工作了几次(我看到它至少循环了 3 或 4 次)。
我有一个调试 printf,即使在程序窗口停止响应后,它仍然可以正常工作。
我最初以为我可能会检查 gSpriteClips,但在 printf 中我总是看到数字等于或低于 7。
有没有人发现我遗漏的任何明显问题?
谢谢。
【问题讨论】: