如何在libgdx中获取模型实例的边界框?

时间:2014-01-05 10:34:07

标签: android libgdx

我创建了一个模型(一个盒子)和100个实例,在世界各地移动。它们会被渲染到预期的位置。

我现在正在尝试实现光线拾取,但我发现所有100个实例都返回原始模型的相同边界框。为什么不为每个实例计算实际的边界框?

创建模型和实例:

public static void createModel() {
   ModelBuilder modelBuilder = new ModelBuilder();
   modelBuilder.begin();
   MeshPartBuilder tileBuilder;
   tileBuilder = modelBuilder.part("top", GL10.GL_TRIANGLES, Usage.Position | Usage.Normal | Usage.TextureCoordinates, new Material(ColorAttribute.createDiffuse(Color.WHITE)));
   tileBuilder.rect(-0.45f, 0.1f, 0.45f,   0.45f, 0.1f, 0.45f,    0.45f, 0.1f, -0.45f,  -0.45f, 0.1f, -0.45f,  0f, 1f, 0f);
   tileBuilder = modelBuilder.part("bottom", GL10.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(ColorAttribute.createDiffuse(Color.WHITE)));
   tileBuilder.rect(-0.45f, 0f, -0.45f,    0.45f, 0f, -0.45f,     0.45f, 0f, 0.45f,     
...
   modelTile = modelBuilder.end();
}

public void createModelInstance(com.badlogic.gdx.assets.AssetManager assetManager) {
  Texture texTile = assetManager.get("textures/" + textureFile, Texture.class);
  Material mat = new Material(TextureAttribute.createDiffuse(texTile));
  modelInstance = new ModelInstance(modelTile); 
  modelInstance.nodes.get(0).parts.get(0).material.set(mat);
}

移动模型实例:

public void setCoordinates(boolean animate, float x, float y, float z) {
  modelInstance.transform.setToTranslation(x,y,z);
  modelInstance.calculateTransforms();
}

射线拣选尝试:

public boolean pickTile(int x, int y) {
  cam.update();
  Ray ray = cam.getPickRay(x, y);
  BoundingBox bb = new BoundingBox();
  for (int i=0;i<gameData.tiles.length;i++) {
    Log.i("ltower", "checking " + i);
    gameData.tiles[i].getModelInstance().calculateBoundingBox(bb);
Log.i("ltower", "BB: " + bb.getCenter().x + "," + bb.getCenter().y + "," + bb.getCenter().z);
    if (Intersector.intersectRayBoundsFast(ray, bb)) {
      gameData.tiles[i].select();
      return true;
    }
  }
  return false;
}

日志:

01-05 05:27:18.934: I/ltower(2175): checking 0
01-05 05:27:18.984: I/ltower(2175): BB: 0.0,0.05,0.0
01-05 05:27:19.024: I/ltower(2175): checking 1
01-05 05:27:19.024: I/ltower(2175): BB: 0.0,0.05,0.0
01-05 05:27:19.044: I/ltower(2175): checking 2
01-05 05:27:19.064: I/ltower(2175): BB: 0.0,0.05,0.0
01-05 05:27:19.064: I/ltower(2175): checking 3
01-05 05:27:19.064: I/ltower(2175): BB: 0.0,0.05,0.0
01-05 05:27:19.064: I/ltower(2175): checking 4
01-05 05:27:19.064: I/ltower(2175): BB: 0.0,0.05,0.0
01-05 05:27:19.064: I/ltower(2175): checking 5
01-05 05:27:19.104: I/ltower(2175): BB: 0.0,0.05,0.0
01-05 05:27:19.104: I/ltower(2175): checking 6
01-05 05:27:19.104: I/ltower(2175): BB: 0.0,0.05,0.0 
...

1 个答案:

答案 0 :(得分:5)

由于您只是创建相同 Model的多个实例,因此它们也具有相同的BoundingBox。边界框将只是模型局部坐标系顶点周围的边界框。

这意味着您需要使用BoundingBox.mul()将模型实例的位置,比例和旋转应用到边界框。