无法在Model或ModelInstance上计算BoundingBox()

时间:2014-08-09 05:55:48

标签: java nullpointerexception libgdx box bounding

我有一小段代码,根据传递给它的模型创建一个ModelInstance等(请原谅所有未使用的变量,如w,h,d,它们来自之前的测试)

package com.mygdx.game;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.loaders.ModelLoader;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.loader.ObjLoader;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.collision.BoundingBox;

public class Shape {
    float w,h,d;
    Color clr;
    Vector3 pos;
    Model shape;
    ModelInstance shapeInst;
    BoundingBox bounds;
    boolean empty;
    public Shape(float width, float height, float depth, Color color, Vector3 position, String model){
        empty = false;
        @SuppressWarnings("rawtypes")
        ModelLoader loader = new ObjLoader();
        shape = loader.loadModel(Gdx.files.internal(model));
        w = width;
        h = height;
        d = depth;
        clr = color;
        pos = position;
        shapeInst = new ModelInstance(shape);
        shapeInst.materials.get(0).set(ColorAttribute.createDiffuse(clr));
        shapeInst.transform.setToTranslation(pos);
        shapeInst.calculateBoundingBox(bounds);
    }
    public Shape(){
        empty = true;
    }
}

但是,无论何时运行,我都会收到此错误:

Exception in thread "LWJGL Application" java.lang.NullPointerException
    at com.badlogic.gdx.graphics.g3d.ModelInstance.calculateBoundingBox(ModelInstance.java:383)
    at com.mygdx.game.Shape.<init>(Shape.java:37)
    at com.mygdx.game.worldRenderer.<init>(worldRenderer.java:62)
    at com.mygdx.game.GDXGame.create(GDXGame.java:92)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:136)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)

它似乎无法计算我指定的ModelInstance的边界框。 Mabye我只是做错了什么,对于如何使用calculateBoundingBox()方法

,我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

请参阅方法calculateBoundingBox的源代码(libgdx是开源的,您可以查看所有代码; - ):

/** Calculate the bounding box of this model instance. This is a potential slow operation, it is advised to cache the result.
 * @param out the {@link BoundingBox} that will be set with the bounds.
 * @return the out parameter for chaining */
public BoundingBox calculateBoundingBox (final BoundingBox out) {
    out.inf(); // here is line 383 !
    return extendBoundingBox(out);
}

stacktrace在第383行抱怨NullPointerException:out.inf();此时我们知道out必须指向null。

现在让我们看看为什么:检查行shapeInst.calculateBoundingBox(bounds);参数bounds为null,因为你忘了初始化它。 (你刚刚声明了边界,但从未将值赋予它)。