在jME3中,场景图是一个树状结构,它组织和控制所有可见和可听到的对象在3D世界中的位置、旋转和缩放。这一章,我们将深入探讨场景图的基本概念:节点(Node)、几何体(Geometry)和空间(Spatial)。这些是构建和管理复杂3D场景的关键组件。
节点(Node)
节点是场景图中最基本的组织单元,它可以包含其他节点或几何体。节点主要用于组织场景层次结构和控制对象的变换(位置、旋转和缩放)。
Node myNode = new Node("Node Name");
myNode.setLocalTranslation(x, y, z); // 设置位置
myNode.setLocalRotation(rotation); // 设置旋转
myNode.setLocalScale(scale); // 设置缩放
几何体(Geometry)
几何体是场景图中的叶节点,它代表一个具体的3D对象,如3D模型、文本或粒子系统。几何体由形状(Shape)和材质(Material)组成。
Geometry myGeometry = new Geometry("Geometry Name", myShape);
Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", ColorRGBA.Blue);
myGeometry.setMaterial(mat);
rootNode.attachChild(myGeometry);
空间(Spatial)
空间是场景图中的抽象类,节点和几何体都继承自空间。空间可以包含变换信息,并且可以被添加到场景图中。
Spatial mySpatial = new Node("Spatial Name");
mySpatial.setLocalTranslation(x, y, z);
rootNode.attachChild(mySpatial);
包 com.jme3.scene.shape 下的示例
Box
创建一个简单的3D盒子。
// 创建一个立方体
Geometry box = new Geometry("Box", new Box(1, 1, 1));
Material boxMat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
boxMat.setColor("Color", ColorRGBA.Red);
box.setMaterial(boxMat);
rootNode.attachChild(box);
Sphere
创建一个3D球体。
// 创建一个半径为1,有32个环面和64个纵面片的球体
Geometry sphere = new Geometry("Sphere", new Sphere(32, 32, 1));
Material sphereMat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
sphereMat.setColor("Color", ColorRGBA.Blue);
sphere.setMaterial(sphereMat);
sphere.setLocalTranslation(0, 2, 0);
rootNode.attachChild(sphere);
Cylinder
创建一个3D圆柱体。
Cylinder cylinder = new Cylinder(32, 32, 1, 2, true); // 创建一个底面半径为1,顶面半径为2,高为3的圆柱体
Material cylinderMat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
cylinderMat.setColor("Color", ColorRGBA.Brown);
Geometry cylinderGeom = new Geometry("Cylinder", cylinder);
cylinderGeom.setMaterial(cylinderMat);
rootNode.attachChild(cylinderGeom);
Torus
创建一个3D圆环。
Torus torus = new Torus(16, 16, 2, 1); // 创建一个主半径4,次半径2的圆环
Material torusMat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
torusMat.setColor("Color", ColorRGBA.Yellow);
Geometry torusGeom = new Geometry("Torus", torus);
torusGeom.setMaterial(torusMat);
rootNode.attachChild(torusGeom);
Quad
创建一个3D平面。
// 创建一个平面,大小为5x5
Quad quad = new Quad(5, 5);
Geometry quadGeom = new Geometry("CenterQuad", quad);
// 创建材质并加载纹理
Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
Texture texture = assetManager.loadTexture("Textures/Terrain/PBR/Gravel015_1K_AmbientOcclusion.png"); // 替换为你的纹理路径
mat.setTexture("ColorMap", texture);
quadGeom.setMaterial(mat);
// 设置Quad的位置,使其居中
quadGeom.setLocalTranslation(0, 0, 0); // 将Quad放置在原点
// 将Quad添加到场景中
rootNode.attachChild(quadGeom);
结论
通过本章的学习,你现在应该对jME3的场景图有了基本的了解,包括节点、几何体和空间的概念和用法。这些知识将为你创建更复杂和动态的3D场景打下坚实的基础。