It's time to throw in a little more excitement. Let's animate the cube so that it rotates. This'll help demonstrate the shading as well.
For this, we need a Time
class. This is a singleton utility class that ticks off frames and makes that information available to the application, for example, via getDeltaTime
. Note that this is a final
class, which explicitly means that it cannot be extended. There is no such thing as a static class in Java, but if we make the constructor private, we can ensure that nothing will ever instantiate it.
Create a new Time
class in the renderbox/
folder. It won't be getting extended, so we can declare it final
. Here's the code:
public final class Time { private Time(){} static long startTime; static long lastFrame; static long deltaTime; static int frameCount; protected static void start(){ frameCount = 0; startTime = System.currentTimeMillis(); lastFrame = startTime; } protected static void update(){ long current =System.currentTimeMillis(); frameCount++; deltaTime = current - lastFrame; lastFrame = current; } public static int getFrameCount(){return frameCount;} public static float getTime(){ return (float)(System.currentTimeMillis() - startTime) / 1000; } public static float getDeltaTime(){ return deltaTime * 0.001f; } }
Start the timer in the RenderBox
setup:
public RenderBox(Activity mainActivity, IRenderBox callbacks){
...
Time.start();
}
Then, in the onNewFrame
method of RenderBox
, call Time.update()
:
public void onNewFrame(HeadTransform headTransform) {
Time.update();
...
}
Now, we can use it to modify the cube's transform each frame, via the preDraw()
interface hook. In MainActivity
, make the cube rotate 5 degrees per second about the X axis, 10 degrees on the Y axis, and 7.5 degrees on the Z axis:
public void preDraw() { float dt = Time.getDeltaTime(); cube.rotate(dt * 5, dt * 10, dt * 7.5f); }
The getDeltaTime()
method returns the fraction of a second since the previous frame. So, if we want it to rotate 5 degrees around the X axis each second, we multiply deltaTime
by 5 to get the fraction of a degree to turn this particular frame.
Run the app. Rock and roll!!!