libGDX确实可以创建一个对象吗?

时间:2015-06-29 17:27:25

标签: java foreach libgdx

我正在通过这些tutourials学习g3d:https://xoppa.github.io/blog/using-materials-with-libgdx/

现在我听说foreach循环创建了一个对象,并且在渲染方法中使用起来很糟糕。

示例:

private PerspectiveCamera cam;
private CameraInputController camController;
private Shader shader;
private Model model;
private Array<ModelInstance> instances = new Array<ModelInstance>();
private ModelBatch modelBatch;

@Override
public void show() {
    cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    cam.position.set(2f, 2f, 2f);
    cam.lookAt(0, 0, 0);
    cam.near = 1f;
    cam.far = 300f;
    cam.update();

    camController = new CameraInputController(cam);
    Gdx.input.setInputProcessor(camController);

    ModelBuilder modelBuilder = new ModelBuilder();
    model = modelBuilder.createSphere(2f, 2f, 2f, 20, 20,
            new Material(),
            VertexAttributes.Usage.Position |
                    VertexAttributes.Usage.Normal |
                    VertexAttributes.Usage.TextureCoordinates);

    for (int x = -5; x <= 5; x+=2) {
        for (int z = -5; z <= 5; z+=2) {
            instances.add(new ModelInstance(model, x, 0, z));
        }
    }

    shader = new TestShader();
    shader.init();

    modelBatch = new ModelBatch();
}

@Override
public void render(float delta) {
    camController.update();

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

    modelBatch.begin(cam);
    for (ModelInstance instance : instances) {
        modelBatch.render(instance, shader);
    }
    modelBatch.end();

}
  1. 这是真的吗?它会创建一个对象吗?
  2. 什么是解决方案?

1 个答案:

答案 0 :(得分:1)

不,它不会创建对象。 for-each循环只是一个语法快捷方式。见Does the Java foreach loop create a new object?