0

所以我只是从 LIBGDX 的 3D 部分开始。我下载了最新的夜间版本,当我按照教程进行操作时,我在一行上得到了一个 nullPointerException(这将在代码中标记)。线上有一个nullPointer就是这个代码

modelBatch.render(instance);

这条线的所有值都在那里。该实例具有其所有属性以及我的代码中的几乎所有其他属性。为什么我得到一个 nullPointerException 的任何想法?提前致谢。

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.materials.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.materials.Material;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;


public class threeDTest implements ApplicationListener {
public PerspectiveCamera camera;
public ModelBatch modelBatch;
public Model model;
public ModelInstance instance;

    @Override
    public void create() {
        camera =  new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        camera.position.set(10f, 10f, 10f);
        camera.lookAt(0, 0, 0);
        camera.near = 0.1f;
        camera.far = 300f;
        camera.update();

    ModelBuilder modelBuilder = new ModelBuilder();
    model = modelBuilder.createBox(5f, 5f, 5f, 
        new Material(ColorAttribute.createDiffuse(Color.GREEN)),
        Usage.Position | Usage.Normal);
    instance = new ModelInstance(model);
    }

    @Override
    public void resize(int width, int height) {

    }

    @Override
    public void render() {  
        Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

        modelBatch.begin(camera);//Begin Rendering
        modelBatch.render(instance);<--Null Pointer on this line
        modelBatch.end();//End Rendering
    }

@Override
public void pause() {

}

@Override
    public void resume() {

    }

    @Override
    public void dispose() {
        model.dispose();
    }

}

4

1 回答 1

3

查看您的代码,您永远不会构造(和处置)modelBatch 实例。因此 modelBatch 将为空,导致您得到 NPE。

在您的 create 方法中添加以下行:

modelBatch = new ModelBatch();

以及您的 dispose 方法中的以下行:

modelBatch.dispose();
于 2013-07-18T15:26:21.753 回答