SDL在屏幕上显示得分

时间:2015-07-12 06:46:51

标签: c++ sdl-2 pong sdl-ttf

使用Pong克隆。尝试在屏幕上显示分数时遇到严重问题。我发现的很多东西都在使用图片,但我只是想用文字显示分数。我尝试使用SDL TTF库来加载字体并显示它但它无法正确显示。我发现了这个问题How to blit Score on screen in SDL?并且回复说使用了SDL_BlitSurface()我尝试过,我只是出现了构建错误(假设我正确地做了)

这是我打电话给得分的功能:

void Pong::drawScore(){
    leftScoreChar = leftScore;
    rightScoreChar = rightScore;

    SDL_Color text_color = {255, 255, 255};

    score = TTF_RenderText_Solid(font,
                                 &leftScoreChar,
                                 text_color);

    score2 = TTF_RenderText_Solid(font,
                                 &rightScoreChar,
                                 text_color);

    leftScoreText = SDL_CreateTextureFromSurface(renderer, score);
    rightScoreText = SDL_CreateTextureFromSurface(renderer, score2);

    SDL_RenderCopy(renderer, leftScoreText, NULL, &scoreA);
    SDL_RenderCopy(renderer, rightScoreText, NULL, &scoreB);
}

运行时输出: https://goo.gl/dZxDEa

Aplogies,我会在帖子中放一张图片,但显然我不能。

除非由于某种原因使得存储得分的整数等于1并且显示为零,否则得分不会显示。并且得分正在逐渐增加,因为我将游戏输出得分到控制台以确保。那么我做错了什么导致我的分数显示不正确并且有一些东西?

1 个答案:

答案 0 :(得分:1)

有很多方法可以做到这一点。 您可以通过SDL_SurfaceSDL_Texture 来完成。我将说明两者。 (根据需要进行调整。)

int fontsize = 24;
int t_width = 0; // width of the loaded font-texture
int t_height = 0; // height of the loaded font-texture
SDL_Color text_color = {0,0,0};
string fontpath = "my font path";
string text = "text I want to display";
TTF_Font* font = TTF_OpenFont(fontpath.c_str(), fontsize);
SDL_Texture* ftexture = NULL; // our font-texture

// check to see that the font was loaded correctly
if (font == NULL) {
    cerr << "Failed the load the font!\n";
    cerr << "SDL_TTF Error: " << TTF_GetError() << "\n";
}
else {
    // now create a surface from the font
    SDL_Surface* text_surface = TTF_RenderText_Solid(font, text.c_str(), text_color);

    // render the text surface
    if (text_surface == NULL) {
        cerr << "Failed to render text surface!\n";
        cerr << "SDL_TTF Error: " << TTF_GetError() << "\n";
    }
    else {
        // create a texture from the surface
        ftexture = SDL_CreateTextureFromSurface(renderer, text_surface);

        if (ftexture == NULL) {
            cerr << "Unable to create texture from rendered text!\n";
        }
        else {
            t_width = text_surface->w; // assign the width of the texture
            t_height = text_surface->h; // assign the height of the texture

            // clean up after ourselves (destroy the surface)
            SDL_FreeSurface(surface);
        }
    }
}

注意,您可以单独停止仅使用表面。然而,由于表面是软件渲染的,因此纹理在VRAM中加载时可以说更好。 (在此处阅读更多内容:Difference between surface and texture (SDL / general)

然后,您所要做的就是渲染它(类似于此):

int x = 0;
int y = 0;
SDL_Rect dst = {x, y, t_width, t_height};
SDL_RenderCopy(renderer, ftexture, NULL, &dst); // renderer is a variable of the type `SDL_Renderer*`

最后,请记住显示事物的顺序很重要!