c++ - SDL_Delay 在 for 循环中不起作用

标签 c++ sdl truetype sdl-ttf

出于某种原因,我的循环无法正常工作。我正在尝试创建慢速输入文本,但它只是同时打印。慢速打印文本,我的意思是像角色扮演游戏的对话。

这是我的代码:

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;
}

最佳答案

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

(很抱歉回答很短,我没有足够的代表发表评论)。

关于c++ - SDL_Delay 在 for 循环中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33531999/

相关文章:

sdl - 实际的 SDL2 硬件要求是什么?

用于处理字体文件的 C# 库 - TTF (TrueType),其他

java - JTextArea 中的日语

c++ - 删除一个类的所有成员

c++ - 消除连接字符串的硬编码

c++ - 如何在 arrayfire 中使用翻转和转置来避免 memcpy?

c++ - 如何在 C++ 中将自定义值范围分配给字符串字符?

windows - Qt Creator 对 SDL_Init 的 undefined reference

graphics - 用于 2D 绘图的 Haskell 库

Python3如何安装.ttf字体文件?