我的游戏开始冻结一段时间后(采取太多的内存),我想尝试绘制3(稍后更多)字符串使用循环方法。我的代码是:

    public class Simple implements ApplicationListener {
        private OrthographicCamera camera;
        private SpriteBatch batch;
        private BitmapFont font;
        private GlyphLayout layout;
        String a1 = "aa";
        String a2 = "bb";
        String a3 = "cc";
        int a = 0;

        @Override
        public void create() {
            camera = new OrthographicCamera();
            camera.setToOrtho(false, 800, 480);
            batch = new SpriteBatch();
        }

        @Override
        public void render() {
            Gdx.gl.glClearColor(0, 0, 0.2f, 1);
            Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
            camera.update();
            batch.setProjectionMatrix(camera.combined);
            batch.begin();
            for (int i = 1; i < 4; i++) {
                layout = new GlyphLayout();
                font = new BitmapFont();
                layout.setText(font, "a" + i);
                font.draw(batch, layout, 200 + (15 * i), 200);
            }
            batch.end();
        }
    }

最佳答案

想象一下Epicpandaforce在评论中提到的内容:

public class Simple implements ApplicationListener {
    private OrthographicCamera camera;
    private SpriteBatch batch;
    private BitmapFont font;
    private GlyphLayout layout;
    String a1 = "aa";
    String a2 = "bb";
    String a3 = "cc";
    int a = 0;

    @Override
    public void create() {
        camera = new OrthographicCamera();
        camera.setToOrtho(false, 800, 480);
        batch = new SpriteBatch();
        //Initialize the fields in create()
        layout = new GlyphLayout();
        font = new BitmapFont();

    }

    @Override
    public void render() {
        Gdx.gl.glClearColor(0, 0, 0.2f, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        camera.update();
        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        for (int i = 1; i < 4; i++) {
            //Use them like you do.
            layout.setText(font, "a" + i);
            font.draw(batch, layout, 200 + (15 * i), 200);
        }
        batch.end();
    }
}

我不确定这是否可行。您没有在任何地方指定位图字体,因此当您使用布局绘制时,可能会得到nullPointerException。在create方法中,您可能希望用font = new BitmapFont(Gdx.files.internal("Path to bitmapfont"));初始化字体。
使用新的是一个昂贵的操作。update()方法在每一帧都被调用,每次调用时都会创建新对象。除此之外,BitmapFont()不是一个小物体。每次为字体和布局创建新对象时,垃圾收集器都需要收集它保存的上一个对象。一个基本规则是永远不要在new方法中使用update()关键字,而是像我刚才那样更改和/或使用它。要以非常简单的方式将其可视化:
Object o; // <-- a simple container
new Object(); // <-- a object stored in memory in all it's glory

Object o = new Object(); // <-- container o is now pointing to the memory address of new Object()

Object o = new Object(); // container 0 is now pointing to a different object in memory
//But the old one is still chilling at it's own address and needs to be collected

关于java - 一段时间后,libgdx游戏开始卡住,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35081427/

10-12 13:30