SDL_Delay不在for循环中工作

时间:2015-11-04 21:06:26

标签: c++ sdl true-type-fonts sdl-ttf

出于某种原因,我的循环不起作用。我试图创建慢速输入文本但它只是同时打印。通过慢速打印文字,我的意思是RPG的对话。

这是我的代码:

void printToConsole(std::string message, std::string &text){
    for(int i = 0; i < message.length(); i++){
        text += message[i];
        SDL_Delay(30);
    }
}

如果需要,这是我的完整代码:

#include<iostream>
#include<SDL.h>
#include<string>
#include<SDL_ttf.h>

void handleEvents(SDL_Event e, bool* quit){
    while(SDL_PollEvent(&e) > 0){
        if(e.type == SDL_QUIT){
            *quit = true;
        }
    }
}

void render(SDL_Renderer* renderer, SDL_Texture* textToRender, SDL_Rect srcrect, SDL_Rect dstrect){
    SDL_RenderClear(renderer);

    SDL_RenderCopy(renderer, textToRender, &srcrect, &dstrect);

    SDL_RenderPresent(renderer);
}

void printToConsole(std::string message, std::string &text){
    for(int i = 0; i < message.length(); i++){
        text += message[i];
        SDL_Delay(30);
    }
}

void start(std::string &text){
    printToConsole("Hey ;)", text);
}

int main( int argc, char *argv[] ) {
    SDL_Init(SDL_INIT_EVERYTHING);
    TTF_Init();
    SDL_Window* window = SDL_CreateWindow("Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 600, 600, SDL_RENDERER_ACCELERATED);
    SDL_Renderer* renderer = SDL_CreateRenderer(window, 0, 0);

    std::string text; //This is the text that has been rendered.
    bool quit = false;
    SDL_Event e;

    TTF_Font* font = TTF_OpenFont("Hack-Regular.ttf", 28);
    SDL_Color color = {255, 255, 255};
    SDL_Surface* textSurface;
    SDL_Texture* textTexture;

    SDL_Rect srcrect;
    SDL_Rect dstrect;

    srcrect.x = 0;
    srcrect.y = 0;
    srcrect.w = 100;
    srcrect.h = 32;
    dstrect.x = 10;
    dstrect.y = 10;
    dstrect.w = 100;
    dstrect.h = 32;

    while(!quit){
        handleEvents(e, &quit);
        render(renderer, textTexture, srcrect, dstrect);

        start(text);

        textSurface = TTF_RenderText_Solid(font, text.c_str(), color);
        textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
    }

    SDL_DestroyWindow(window);
    SDL_DestroyRenderer(renderer);

    window = NULL;
    renderer = NULL;
    TTF_Quit();
    SDL_Quit();
    return 0;
}

1 个答案:

答案 0 :(得分:1)

您应该为添加的每个新角色重新渲染文本,而不是慢慢复制它,然后再渲染它。

(对不起,简短的回答,我没有足够的代表发表评论)。