Frequently Asked Questions¶
I want to create and configure a jME3 Application¶
How do I start writing a preconfigured jME game?¶
Create a project with the Initializer, then write a Java class that extends com.jme3.app.SimpleApplication.
Learn more:
How do I change the background color?¶
viewPort.setBackgroundColor(ColorRGBA.Blue);
Can I customize the SimpleApplication class?¶
Yes! Actually, you MUST customize it! For your own games, you always create a custom base class that extends com.jme3.app.SimpleApplication class. From now on it’s no longer a simple application – it’s now your game. Configure your application settings, implement methods, and customize away!
Learn more:
How can I switch between screens or states?¶
You should break down your application logic into components by spreading it out over individual AppStates. AppStates can be attached to and detached from the game. AppStates receive an Application reference and can access its public services; pass or obtain any additional dependencies they need. So each AppState can bring its own subset of input handlers, GUI nodes, spatial nodes, and even its own subset of game mechanics in the update() loop.
Learn more:
How do I pause/unpause a game?¶
You split up your application into several AppStates and implement the setEnabled() methods for each state. Then you create, for example, a GameRunningAppState and a GamePausedAppState. GamePausedAppState’s job is to attach all your AppStates that contain the logic and GUI of the pause screen, and to detach all the AppStates that contain logic and GUI of the running game. GameRunningAppState does the opposite. By attaching one or the other to the game, you switch between the paused and unpaused states.
Learn more:
How do I disable logger output to the console?¶
During development, you can switch the severity level of the default logger to no longer print FINE warnings, but only WARNINGs.
java.util.logging.Logger.getLogger("").setLevel(Level.WARNING);
For the release, switch the severity level of the default logger to print only SEVERE errors.
java.util.logging.Logger.getLogger("").setLevel(Level.SEVERE);
Learn more:
Why does the executable crash with "Cannot locate resource"?¶
Check that the asset key matches the packaged path, including filename case, and that its loader module and referenced textures or buffers are included. Projects generated by the Initializer can package glTF directly; conversion to .j3o is optional. A ZIP used as an external file must also be distributed at the path registered with its locator.
Learn more:
What is a native library version mismatch?¶
A native library version mismatch can occur when the Java dependencies and the native libraries loaded at runtime come from incompatible versions. Check your project's dependency versions and any explicitly configured native library paths, then rebuild and test the packaged application.
I want to load my scene¶
How do I make objects appear / disappear in the 3D scene?¶
To make a spatial appear in the scene, you attach it to the rootNode (or to a node that is attached to the rootnode). To remove a spatial, you detach it from its parent node.
rootNode.attachChild(spatial); // appear in scene
rootNode.detachChild(spatial); // remove from scene
Learn more:
Why do I get AssetNotFoundException when loading X ?¶
First check whether the file path of the asset is correct. Asset keys are relative to a registered resource root. In a project generated by the Initializer, shared resources normally live under game-assets/src/main/assets:
// Supply this model under game-assets/src/main/assets/Models/Ship/.
Spatial model = assetManager.loadModel("Models/Ship/ship.glb");
For resources outside the classpath, register an appropriate locator with the AssetManager. Different Locator types are available.
this.assetManager.registerLocator("/path/to/external/assets", FileLocator.class);
this.assetManager.registerLocator("c:/jme3User/JMEisSoCool/myAwesomeFolder/", FileLocator.class);
this.assetManager.registerLocator("town.zip", ZipLocator.class);
Note that you should not register every single folder containing a texture as the assetmanager will not be able to discern between images with the same name anymore.
Learn more: Asset Manager
How do I Create 3-D models, textures, sounds?¶
Follow our best practices for the multi-media asset pipeline.
You create 3-D models in a 3-D mesh editor, for example Blender, and export it in one of the 3D model Supported External File Types such as GLTF (animated objects, scenes) or Wavefront OBJ format (static objects, scenes). You create textures in a graphic editor, for example Gimp, and export them as PNG or JPG. You create sounds in an audio editor, for example, Audacity, and export them as WAVE or OGG.
Learn more:
How do I load a 3-D model into the scene?¶
Export a glTF model and place it under the project resource root along with any referenced files. Include jme3-plugins, then load the asset by its relative key. Conversion to .j3o is optional.
// Supply your own model at this resource path.
Spatial model = assetManager.loadModel("Models/Ship/ship.glb");
Learn more:
Code sample:
How to initialize the scene?¶
Use the simpleInitApp() method in SimpleApplication (or initApp() in Application).
Learn more:
I want to transform objects in the scene¶
How do I move or turn or resize a spatial?¶
To move or turn or resize a spatial you use transformations. You can concatenate transformations (e.g. perform rotations around several axes in one step using a Quaternion with slerp() or a com.jme3.math.Transform with interpolateTransforms().
spatial.setLocalTranslation(1,-3,2.5f); spatial.rotate(0,3.14f,0); spatial.scale(2,2,2);
Learn more:
How do I make a spatial move by itself?¶
Change the geometry’s translation (position) live in the update loop using setLocalTranslation() for non-physical and applyForce() or setWalkDirection() for physical objects. You can also define and remote-control a spatial’s motion using Cinematics, e.g. to record cutscenes, or to implement mobile platforms, elevators, airships, etc.
Learn more:
Code sample:
How do I access a named sub-mesh in Model?¶
Geometry submesh = (Geometry) model.getChild("door 12");
Learn more:
How do I make procedural or custom shapes?¶
You can programmatically create com.jme3.scene.Mesh’es.
Learn more:
I want to change the surface of objects in the scene¶
Why is my UV wrapping / texture appearance all wrong?¶
The most likely reason is the flipping of textures. You may be using the following default method:
material.setTexture("ColorMap", assetManager.loadTexture("myTexture.jpg"));
You can set the boolean value in the constructor of TextureKey to flipped or not flipped. Toggle the boolean to see if it fixes your UV wrapping/texture problem:
material.setTexture("ColorMap", this.assetManager.loadTexture(new TextureKey("myTexture.jpg", false)));
How do I scale, mirror, or wrap a texture?¶
You cannot scale a texture, but you scale the texture coordinates of the mesh the texture is applied to:
mesh.scaleTextureCoordinates(new Vector2f(2,2));
You can choose among various com.jme3.texture.Texture.WrapModes for individual texture maps of a material: BorderClamp, EdgeClamp, Clamp; MirrorBorderClamp, MirrorEdgeClamp, MirrorClamp; Repeat, MirroredRepeat.
material.getTextureParam("DiffuseMap").getTextureValue().setWrap(WrapMode.Repeat);
How do I change color or shininess of an material?¶
Use the AssetManager to load Materials, and change material settings.
Learn more:
Code sample:
How do I make a surface wood, stone, metal, etc?¶
Create Textures as image files. Use the AssetManager to load a Material and use texture mapping for improved looks.
Learn more:
Code sample:
Why are materials too bright, too dark, or flickering?¶
If you use a lit material (based on Lighting.j3md) then you must attach a light source to the rootNode, otherwise you see nothing. If you use lit material colors, make sure you have specified an Ambient color (can be the same as the Diffuse color) if you use an AmbientLight. If you see objects, but they are gray or too dark, set the light color to white, or make it brighter (you can multiply the color value with a scalar), or add a global white light source (AmbientLight). Similarly, if everything is too white, tune down the lights. If materials flicker under a directional light, change the light direction vector. Change the background color (which is independent of light sources) to get a better contrast while debugging a light problem.
How do I make geometries cast a shadow?¶
Use com.jme3.shadow.BasicShadowRenderer together with com.jme3.light.DirectionalLight, and setShadowMode().
Learn more:
Code sample:
How do I make materials transparent?¶
Assign a texture with an alpha channel to a Material and set the Material’s blend mode to alpha. Use this to create transparent or translucent materials such as glass, window panes, water, tree leaves, etc.
material.getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
Learn more:
How do I force or disable culling?¶
While debugging custom meshes, you can switch the com.jme3.material.RenderState.FaceCullMode off to see the inside and outside of the mesh.
someMaterial.getAdditionalRenderState().setFaceCullMode(FaceCullMode.Off);
You can also deactivate the com.jme3.scene.Spatial.CullHint of a whole spatial to force jme to calculate it even if it is behind the camera and outside of view.
someNode.setCullHint(CullHint.Never);
Learn more:
Can I draw only an outline of the scene?¶
Add a renders state to the material’s and activate Wireframe.
material.getAdditionalRenderState().setWireframe(true);
Learn more:
I want to control the camera¶
The default camera cam is an instance of the Camera class.
Learn more:
How do I keep the camera from moving?¶
SimpleApplication activates flyCam (an instance of FlyByCamera) by default. flyCam causes the camera to move with the mouse and the WASD keys. You can disable flyCam as follows:
flyCam.setEnabled(false);
How do I switch between third-person and first-person view ?¶
You can activate the FlyBy Cam as a first-person camera.
flyCam.setEnabled(true);
Learn more:
Code sample:
You can also create a third-person chase cam.
flyCam.setEnabled(false);
chaseCam = new ChaseCamera(cam, spatial, inputManager);
Learn more:
Code sample:
jme3test/input/TestChaseCamera.java
How do I increase camera speed?¶
flyCam.setMoveSpeed(50f);
Actions, Interactions, Physics¶
How do I implement game logic / game mechanics?¶
Use Controls to define the behaviour of types of Spatials. Use Application States to implement global behaviour, to group subsets of input handlers or GUI screens, etc. Use the simpleUpdate() and update() loops for tests and interactions. Use Cinematics to remote-control objects in scenes.
Learn more:
How do I let players interact via keyboard?¶
Use com.jme3.input.KeyInput and a Input Listener.
Learn more:
How do I let players interact by clicking?¶
Players typically click the mouse to pick up objects, open doors or shoot a weapon. Use an input listener, then cast a ray into the scene and inspect the returned collision results. The links below contain samples for both fixed crosshairs and a free mouse pointer.
Learn more:
Code sample:
How do I animate characters?¶
Create and export an animated glTF model in a 3D editor, load it, then use its AnimComposer to play the available clips.
Learn more:
Code sample:
How do I keep players from falling through walls and floors?¶
Use collision detection or a physics module to prevent objects from passing through the environment. See Choosing a physics module for available options.
Learn more:
-
CapsuleCollisionShape versus CompoundCollisionShape, CharacterControl versus RigidBodyControl.
How do I make balls/wheels/etc bounce and roll?¶
Add physics controls to Spatials and give them spherical or cylindrical bounding volumes.
Learn more:
Code sample:
How do I debug weird Physics behaviour?¶
Maybe your collision shapes overlap – or they are not where you think they are. Make the collision shapes visible by adding the following line after the bulletAppState initialization:
bulletAppState.setDebugEnabled(true);
How do I make a walking character?¶
A Bullet physics module provides character controls that keep a character upright while it moves and interacts with the environment.
Learn more:
Code Sample:
-
TestQ3.java (first-person)
-
TestPhysicsCharacter.java (third-person)
How do I steer vehicles?¶
Use a VehicleControl that supports suspension behavior.
Learn more:
Code Sample:
- TestFancyCar.java (Press HUJK keys to steer, spacebar to jump.)
Can objects swing like a pendulums, chains, ropebridges?¶
Use a PhysicsControl’s hinges and joints.
Learn more:
-
TestPhysicsHingeJoint.java (Press HK keys to turn, spacebar to swing.)
Default GUI Display¶
What are these FPS/Objects/Vertices/Triangles statistics?¶
At the bottom left of every default SimpleGame, you see the StatsView and the FPS (frames per seconds) view. These views provide you with extra information during the development phase. For example, if you notice the object count is increasing and the FPS is decreasing, then you know that your code attaches too many objects and does not detach enough of them again (maybe a loop gone wild?).
How do I get rid of the FPS/Objects statistics?¶
In the application’s simpleInitApp() method, call:
setDisplayFps(false); // to hide the FPS
setDisplayStatView(false); // to hide the statistics
How do I display score, health, mini-maps, status icons?¶
Attach text and pictures to the orthogonal guiNode to create a heads-up display (HUD).
Learn more:
-
com.jme3.ui.Picture guiNode.attachChild()
Code Sample:
How do I display buttons and UI controls?¶
You may want to display buttons to let the player switch between the game, settings screen, and score screens. For more complex interfaces, try Lemur or browse other community modules. Nifty GUI is another available integration.
Learn more:
Code Sample:
How do i display a loading screen?¶
Instead of having a frozen frame while your games loads, you can have a loading screen while it loads.
Learn more:
Nifty GUI¶
I get NoSuchElementException when adding controls (buttons etc)!¶
Verify that you include a controls definition file link in your XML: This is the default:
<useControls filename="nifty-default-controls.xml"/>
Where can I find example code of Nifty GUI’s XML and Java classes?¶
https://github.com/nifty-gui/nifty-gui
Is there Java Doc for Nifty GUI?¶
I want to create an environment with sounds, effects, and landscapes¶
How do I play sounds and noises?¶
Use AudioRenderer, Listener, and AudioNode from com.jme3.audio..
Learn more:
Code sample:
How do I make fire, smoke, explosions, swarms, magic spells?¶
For swarm like effects you use particle emitters.
Learn more:
Code sample:
How do I make water, waves, reflections?¶
Use a special post-processor renderer from com.jme3.water..
Learn more:
Code sample:
How do I make fog, bloom, blur, light scattering?¶
Use special post-processor renderers from com.jme3.post..
Learn more:
How do I generate a terrain?¶
Use com.jme3.terrain.. The JMonkeyEngine also provides you with a Terrain Editor plugin.
Learn more:
Code sample:
How do I make a sky?¶
Code sample:
Spatial sky = SkyFactory.createSky(assetManager,
"Textures/Sky/studio.hdr", SkyFactory.EnvMapType.EquirectMap);
rootNode.attachChild(sky);
Learn more:
I want to access to back-end properties¶
How do I read out graphic card capabilities?¶
If your game is heavily using features that older cards do not support, you can read graphics capabilities after the renderer initializes and choose a suitable fallback.
Collection<com.jme3.renderer.Caps> caps = renderer.getCaps();
Logger.getLogger(HelloJME3.class.getName()).log(Level.INFO, "Capabilities: {0}", caps.toString());
How do I choose ANGLE or native OpenGL?¶
Set the renderer in AppSettings before the application starts, using the backend and dependencies available in your project. See Rendering and displays for ANGLE, native OpenGL, high-DPI scaling and supersampling.
How do I optimize the heck out of the Scene Graph?¶
You can batch all Geometries in a scene (or a subnode) that remains static.
jme3tools.optimize.GeometryBatchFactory.optimize(rootNode);
Batching means that all Geometries with the same Material are combined into one mesh. This optimization only has an effect if you use only few (roughly up to 32) Materials total. The pay-off is that batching takes extra time when the game is initialized.
How do I prevent users from unzipping my JAR?¶
A JAR is an archive, so players can inspect its contents. Obfuscation can make code harder to read, but cannot keep assets or secrets hidden from someone running the game. Keep secrets on a trusted server.
I want to do maths¶
What does addLocal() / multLocal() etc mean?¶
Many maths functions (mult(), add(), subtract(), etc) come as local and a non-local variant (multLocal(), addLocal(), subtractLocal(), etc).
-
Non-local means a new independent object is created (similar to clone()) as a return value. Use non-local methods if you want to keep using the old value of the object calling the method.
-
Example 1:
Quaternion q1 = q2.mult(q3); -
Returns the result as a new Quaternion q1.
-
The involved objects q2 and q3 stay as they are and can be reused.
-
Example 2:
v.mult(b).add(b); -
Watch out: This calculates the expected result, but unless you actually use the return value, it is discarded!
-
-
Local means that no new objects are created, instead, the calling object is modified. Use this if you are sure you no longer need the old value of the calling object.
-
Example 1:
q2.multLocal(q3) -
Calculates q2*q3 without creating temp objects.
-
The result is stored in the calling object q2. The old value of q2 is gone.
-
Object q3 stays as it was.
-
Example 2:
v.multLocal(a).addLocal(b); -
Calculates the expected result without creating temp objects.
-
The result is stored in the calling object v. The old value of v is gone.
-
The objects a and b stay as they were.
-
What is the difference between World and Local coordinates?¶
World coordinates of a Spatial are its absolute coordinates in the 3D scene (this is like giving GPS coordinates). Local coordinates are relative to the Spatial’s parent Spatial (this is like saying, I’m ten meters left of the entrance).
How do I convert Degrees to Radians?¶
Multiply degree value by FastMath.DEG_TO_RAD to convert it to radians.