Previous: Hello Assets, Next: Hello Input System
Now that you know how to load assets such as 3-D models, you want them to implement the actual gameplay. In this tutorial we look at the update loop. The update loop of your game is where the action happens.
package jme3test.helloworld;
import com.jme3.app.SimpleApplication;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.shape.Box;
/** Sample 4 - how to trigger repeating actions from the main update loop.
* In this example, we make the player character rotate. */
public class HelloLoop extends SimpleApplication {
public static void main(String[] args){
HelloLoop app = new HelloLoop();
app.start();
}
protected Geometry player;
@Override
public void simpleInitApp() {
Box(Vector3f.ZERO, 1, 1, 1);
player = new Geometry("blue cube", b);
Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", ColorRGBA.Blue);
player.setMaterial(mat);
rootNode.attachChild(player);
}
/* This is the update loop */
@Override
public void simpleUpdate(float tpf) {
// make the player rotate
player.rotate(0, 2*tpf, 0);
}
}
Build and run the file: You see a constantly rotating cube.
Compared to our previous code samples you note that the player Geometry is now a class field. This is because we want the update loop to be able to access and transform this Geometry. As you can see, we initialize the player object in the simpleInitApp()
method.
Now have a closer look at the simpleUpdate()
method, this is the update loop.
player.rotate(0, 2*tpf, 0);
line changes the rotation of the player object.tpf
variable ("time per frame") to time this action depending on the current frames per second rate. This means the cube rotates with the same speed on fast machines, and the game remains playable.A rotating object is just a simple example. In the update loop, you can update score and health points, check for collisions, make enemies calculate their next move, roll the dice whether a trap has been set off, play random ambient sounds, and much more.
simpleInitApp()
method has set up the scenegraph and state variables.simpleUpdate()
method repeatedly, as fast as possible.Here are some fun things to try:
tpf
)Look back at the Hello Node tutorial if you do not remember the transformation methods for scaling, translating, and rotating.
Now you are listening to the update loop, "the heart beat" of the game, and you can add all kinds of action to it.
The next thing the game needs is some interaction! Continue learning how to respond to user input.
See also: Advanced jME3 developers additionally use Application States and Custom Controls to implement more complex mechanics in their game loops. You will come across these topics later when you proceed to advanced documentation.