Spatial表示3D空間中的一個物體,它在空間中有三種線性變換:位移(Translation)、旋轉(Rotation)、縮放(Scale)。Spatial是Geometry和Node的父類。
Geometry存儲了物體的網格和材質,代表可視物體。
Node是一個空間中的節點,每個節點(Node)中可以包含多個Spatial,每個Spatial只能有一個父節點(Node)。Node之間通過父子關係形成樹形結構。
public class sphere extends SimpleApplication {
private Spatial spatial;
@Override
public void simpleUpdate(float tpf) {
// TODO Auto-generated method stub
if (spatial != null) {
// 繞Y軸旋轉
spatial.rotate(0, 3.1415926f * tpf, 0);
}
}
@Override
public void simpleInitApp() {
// 球體網格
Mesh mesh = new Sphere(16, 24, 1);
// 創建2個球體
Geometry geomA = new Geometry("藍色氣球", mesh);
geomA.setMaterial(newLightingMaterial(ColorRGBA.Blue));
Geometry geomB = new Geometry("黃色氣球", mesh);
geomB.setMaterial(newLightingMaterial(ColorRGBA.Yellow));
// 將兩個球體添加到一個Node節點中
Node node = new Node("原點");
node.attachChild(geomA);
node.attachChild(geomB);
// 設置兩個球體的相對位置
geomA.setLocalTranslation(-1, 3, 0);
geomB.setLocalTranslation(1.5f, 2, 0);
// 將這個節點添加到場景圖中
rootNode.attachChild(node);
// 添加光源
addLight();
this.spatial = node;
}
/**
* 創建一個感光材質
* @param color
* @return
*/
private Material newLightingMaterial(ColorRGBA color) {
// 創建材質
Material mat = new Material(assetManager, "Common/MatDefs/Light/Lighting.j3md");
mat.setColor("Diffuse", color);
mat.setColor("Ambient", color);
mat.setColor("Specular", ColorRGBA.White);
mat.setFloat("Shininess", 24);
mat.setBoolean("UseMaterialColors", true);
return mat;
}
/**
* 添加光源
*/
private void addLight() {
// 定向光
DirectionalLight sun = new DirectionalLight();
sun.setDirection(new Vector3f(-1, -2, -3));
// 環境光
AmbientLight ambient = new AmbientLight();
// 調整光照亮度
ColorRGBA lightColor = new ColorRGBA();
sun.setColor(lightColor.mult(0.8f));
ambient.setColor(lightColor.mult(0.2f));
// #3 將模型和光源添加到場景圖中
rootNode.addLight(sun);
rootNode.addLight(ambient);
}
public static void main(String[] args) {
sphere app = new sphere();
app.start();
}
}
效果如圖所示: