首页 > 解决方案 > 使用 SFML 从函数中绘制文本

问题描述

我正在尝试使用函数根据输入参数设置要在 SFML 上显示的文本。

该函数是 Text 类型并返回一个文本对象。我添加了cout语句来确定错误发生的位置。正文如下:

#include <string>
#include <iostream>
#include "functions.h"
using namespace std;
#include <SFML/Graphics.hpp>                    // include the SFML Graphics Library
using namespace sf;

Text showPoints(int& points, bool addPoints, bool isPlayer){
    cout << "Function called " << endl;
    string disPoints;
    Text toDisp;
    Font pointFont;
    if(addPoints){
        points += 1;
    }
    cout << "Points added" << endl;
    if(!pointFont.loadFromFile("data/arial.ttf") ){
        cout << "could not load font" << endl;
    }
    cout << "Loaded fonts" << endl;
    if(isPlayer){
        cout << "isPlayer conditional" << endl;
        disPoints = "Player Points: ";
        toDisp.setPosition(50, 800);
        toDisp.setFont(pointFont);
        toDisp.setString(disPoints);
        toDisp.setFillColor(Color::White);
        toDisp.setCharacterSize(30);
    }
    else if(!isPlayer){
        cout << "isAI conditional" << endl;
        disPoints = "AI Points: ";
        toDisp.setPosition(1000, 200);
        toDisp.setFont(pointFont);
        toDisp.setString(disPoints);
        toDisp.setFillColor(Color::White);
        toDisp.setCharacterSize(30);
    }

    cout << "Conditions passed" << endl;
    return toDisp;
}

//usual SFML stuff... under the while(window.isOpen()), before the 
//window.display() and events check

        cout << "Error on function?" << endl;
        window.draw(showPoints(playerPoints, 0, 1));
        cout << "First function passed" << endl;
        window.draw(showPoints(AIPoints, 0, 0));

我希望文本会显示在 SFML 窗口中的适当位置。但是,终端输出这个并且窗口崩溃:

Error on function?
Function called 
Points added
Loaded fonts
isPlayer conditional
Conditions passed

Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

一定是 window.draw() 函数有问题,因为没有调用第二个绘图函数。Text那么在window.draw()中调用类型函数是否合法?如果没有,我该怎么做?谷歌搜索在这个问题上没有任何帮助。

标签: c++sfml

解决方案


推荐阅读