# How to create a Update function in Java

I have recently started using Java, but have been programming in javascript, and actionscript 3 for a while.

I am used to the language giving me the ability to simply do something like:

private function Update(){
//stuff
}


or something similar to that.

I am looking for something similar in Java, and I want to make sure I am doing it correctly.

I started following a tutorial, and they said to do something like this:

 long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while(running){
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1){
tick();
delta--;
}

if(running)
render();
frames++;

if(System.currentTimeMillis() - timer > 1000){
timer += 1000;
System.out.println("FPS: " + frames);
frames = 0;
}
}


This seems to be every second calling the tick() function, not the same as every frame though, and while things tend to happen in less time than a second, I would much rather use the same old frame by frame method i was using. (Unless someone can give me a reason not to, always up for an opinion)

So I am wondering, why not just do something like:

while(running){
Update();
}


I believe this would call every frame. Am I doing something completely crazy here? is there a much better method?

• What is tick() supposed to be doing? – Vaillancourt Jun 17 '15 at 11:02

There is a nuance here. You asked:

So I am wondering, why not just do something like:

while(running){ Update(); }

I believe this would call every frame.

This is false. If you place your Update() method inside a simple while(true) loop, it will be called as much times as the processor can handle. If your processor can run it 123456 times a second, it will.

The method the tutorial you follow is using is called a fixed time-step update. In other words, you call your Update() function X times a second (often 60) at fixed intervals (1/60 or 0.0166... seconds).

By using a simple while(true) loop, you can use a technique called a delta-time update. This technique calls the Update() functions as many times as it can, but passes the time elapsed between 2 loops to the Update() function, so that you can make your calculations accordingly.

There is a lot of documentation on the various advantages and disadvantages of both methods, a quick Google search or a search on this site should give plenty information. But nobody can tell you which one is the ABSOLUTE better.

NOTE: In your example, the Update() function is only running 1 time per second. You'd need to change a line in order to have the 60 updates per second you want:

delta += (now - lastTime) / ns / amountOfTicks;


Move the tick function outside the while loop and next to the render function Then you can even make a whole new function with render and tick if you want.

While (running)

{

Render ();

Tick ();

}