libgdx 通过项目绘制文本绘制两次?

libgdx draw text via project draws twice?

我尝试使用 libgdx 的 camera.project 函数为我的 3D 世界对象绘制 2D 文本,但遇到了一个奇怪的问题。

见下图:

正如您在图片中看到的,图 1 中的一切都很好,但是当我旋转 180 度时,球的名称(代号 1)也在绘制空白 space(图 2)。我不明白问题是什么,经过数小时的思考决定在这里提问。 请帮助我。

我的代码是:

public static void drawNames(){
    TheGame.spriteBatch.begin();
    for(int i = 0; i < TheGame.playerMap.size; i++){
        Player ply = TheGame.playerMap.getValueAt(i);
        if(!ply.isAlive)
            continue;
        TheGame.tmpVec.set(ply.getPos().x, ply.getPos().y, ply.getPos().z);
        TheGame.cam.project(TheGame.tmpVec);
        TheGame.fontArialM.draw(TheGame.spriteBatch, ply.name, TheGame.tmpVec.x, TheGame.tmpVec.y, 0, Align.center, false);
    }
    TheGame.spriteBatch.end();
}

这是因为如果您在相机后面投射某些东西,它仍然会从 project 方法获得有效的屏幕坐标。 考虑以下打印两个世界坐标的屏幕坐标

        PerspectiveCamera camera = new PerspectiveCamera(60, 800, 600);
        camera.position.set(0, 0, -10);
        camera.lookAt(0, 0, 0);
        camera.update();

        Vector3 temp = new Vector3();
        Vector3 p1 = new Vector3(1, 0, 10); // This is in front of the camera, slightly to the right
        Vector3 p2 = new Vector3(0, 0, -100); // This is behind of the camera

        camera.project(temp.set(p1));
        System.out.println("p1 is at screen " + temp);
        if (camera.frustum.pointInFrustum(p1))
            System.out.println("p1 is visible to the camera");
        else
            System.out.println("p1 is not visible to the camera");

        camera.project(temp.set(p2));
        System.out.println("p2 is at screen " + temp);
        if (camera.frustum.pointInFrustum(p2))
            System.out.println("p2 is visible to the camera");
        else
            System.out.println("p2 is not visible to the camera");

在您的代码中,在渲染文本之前,您需要检查 ply.getPos() 矢量是否对相机可见,如果可见则只渲染文本。

if (TheGame.cam.frustum.pointInFrustum(ply.getPos()) {
    TheGame.tmpVec.set(ply.getPos().x, ply.getPos().y, ply.getPos().z);
    TheGame.cam.project(TheGame.tmpVec);
    TheGame.fontArialM.draw(TheGame.spriteBatch, ply.name, TheGame.tmpVec.x, TheGame.tmpVec.y, 0, Align.center, false);
}

请注意,还有其他方法可以更有效地剔除相机后面的东西。