gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:59:39 26 4
gpt4 key购买 nike

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

这是我的代码:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com