Android smooth game loop - java

I have problems with smooth scrolling in OpenGL (testing on SGS2 and ACE)
I created simple applications - only fixed speed horizontal scrolling of images, or only one image (player) moving by accelerator,
but it's movement is not smooth :-(
I tried many various of code but no satisfaction...
first I tried work with GLSurfaceView.RENDERMODE_CONTINUOUSLY and I put all code to onDrawFrame:
public void onDrawFrame(GL10 gl)
{
updateGame(gl, 0.017f);
drawGame(gl);
}
this is the simplest and absolute smooth!! - but it's dependent on hardware speed (= useless)
public void onDrawFrame(GL10 gl)
{
frameTime = SystemClock.elapsedRealtime();
elapsedTime = (frameTime - lastTime) / 1000;
updateGame(gl, elapsedTime);
drawGame(gl);
lastTime = frameTime;
}
this is the best of all but it's not as smooth as the previous, sometimes flick
second I tried GLSurfaceView.RENDERMODE_WHEN_DIRTY, in onDrawFrame i have only drawing objects and this code in separate Thread:
while (true)
{
updateGame(renderer, 0.017f);
mGLSurfaceView.requestRender();
next_game_tick += SKIP_TICKS;
sleep_time = next_game_tick - System.currentTimeMillis();
if (sleep_time >= 0)
{
try
{
Thread.sleep(sleep_time);
}
catch (Exception e) {}
}
else
{
Log.d("running behind: ", String.valueOf(sleep_time));
}
}
this is not smooth and it's not problem with "running behind"
My objective is smooth image movement like in first code example above.
Possible error is somewhere else then I looking. Please, Can somebody help me with this?
Is better use RENDERMODE_WHEN_DIRTY or RENDERMODE_CONTINUOUSLY?
Thank you.

I was fighting with the exact same issue for several days. The loop looks smooth without any Android time reference, but as soon it includes any type of “time sync” , external factors out of the android development control introduce serious discontinuities to the final result.
Basically, these factors are:
eglSwapInterval is not implemented in Android, so is difficult to know the moment when the hardware expose the final draw in the screen (hardware screen sync)
Thread.sleep is not precise. The Thread may sleep more or less than requested.
SystemClock.uptimeMillis()System.nanoTime(), System.currentTimeMillis() and other timing related measurement are not accurate (its precise).
The issue is independent of the drawing technology (drawing, openGL 1.0/1.1 and 2.0) and the game loop method (fixed time step, interpolation, variable time step).
Like you, I was trying Thread.sleep, crazy interpolations, timers, etc. Doesn’t matter what you will do, we don’t have control over this factors.
According with many Q&A on this site, the basic rules to produce smooth continuous animations are:
Reduce at the minimum the GC by removing all dynamic memory request.
Render frames as fast the hardware can process them (40 to 60fps is ok in most android devices).
Use fixed time steps with interpolation or variable time steps.
Optimize the update physics and draw routines to be execute in relative constant time without high peaks variance.
For sure, you made a lot of previous work before post this question by optimizing your updateGame() and drawGame() (without appreciable GC and relative constant execution time) in order to get a smooth animation in your main loop as you mention: “simple and absolute smooth”.
Your particular case with variable stepTime and no special requirements to be in perfect sync with realTime events (like music), the solution is simple: “smooth the step Time variable”.
The solution works with other game loop schemes (fixed time step with variable rendering) and is easy to port the concept (smooth the amount of displacement produced by the updateGame and the real time clock across several frames.)
// avoid GC in your threads. declare nonprimitive variables out of onDraw
float smoothedDeltaRealTime_ms=17.5f; // initial value, Optionally you can save the new computed value (will change with each hardware) in Preferences to optimize the first drawing frames
float movAverageDeltaTime_ms=smoothedDeltaRealTime_ms; // mov Average start with default value
long lastRealTimeMeasurement_ms; // temporal storage for last time measurement
// smooth constant elements to play with
static final float movAveragePeriod=40; // #frames involved in average calc (suggested values 5-100)
static final float smoothFactor=0.1f; // adjusting ratio (suggested values 0.01-0.5)
// sample with opengl. Works with canvas drawing: public void OnDraw(Canvas c)
public void onDrawFrame(GL10 gl){
updateGame(gl, smoothedDeltaRealTime_ms); // divide 1000 if your UpdateGame routine is waiting seconds instead mili-seconds.
drawGame(gl);
// Moving average calc
long currTimePick_ms=SystemClock.uptimeMillis();
float realTimeElapsed_ms;
if (lastRealTimeMeasurement_ms>0){
realTimeElapsed_ms=(currTimePick_ms - lastRealTimeMeasurement_ms);
} else {
realTimeElapsed_ms=smoothedDeltaRealTime_ms; // just the first time
}
movAverageDeltaTime_ms=(realTimeElapsed_ms + movAverageDeltaTime_ms*(movAveragePeriod-1))/movAveragePeriod;
// Calc a better aproximation for smooth stepTime
smoothedDeltaRealTime_ms=smoothedDeltaRealTime_ms +(movAverageDeltaTime_ms - smoothedDeltaRealTime_ms)* smoothFactor;
lastRealTimeMeasurement_ms=currTimePick_ms;
}
// Optional: check if the smoothedDeltaRealTIme_ms is too different from original and save it in Permanent preferences for further use.
For a fixed time step scheme, an intermetiate updateGame can be implemented to improve the results:
float totalVirtualRealTime_ms=0;
float speedAdjustments_ms=0; // to introduce a virtual Time for the animation (reduce or increase animation speed)
float totalAnimationTime_ms=0;
float fixedStepAnimation_ms=20; // 20ms for a 50FPS descriptive animation
int currVirtualAnimationFrame=0; // useful if the updateGameFixedStep routine ask for a frame number
private void updateGame(){
totalVirtualRealTime_ms+=smoothedDeltaRealTime_ms + speedAdjustments_ms;
while (totalVirtualRealTime_ms> totalAnimationTime_ms){
totalAnimationTime_ms+=fixedStepAnimation_ms;
currVirtualAnimationFrame++;
// original updateGame with fixed step
updateGameFixedStep(currVirtualAnimationFrame);
}
float interpolationRatio=(totalAnimationTime_ms-totalVirtualRealTime_ms)/fixedStepAnimation_ms;
Interpolation(interpolationRatio);
}
Tested with canvas and openGlES10 drawing with the following devices: SG SII (57 FPS), SG Note(57 FPS) , SG tab(60 FPS), unbranded Android 2.3 (43 FPS) slow emulator running on Windows XP(8 FPS). The test platform draws around 45 objects + 1 huge background (texture from 70MP source image) moving along a path specified in real physics parameters (km/h and G’s), without spikes or flick between several devices (well, 8 FPS on the emulator doesn’t look good, but its flow at constant speed as expected)
Check The graphs for how android report the time. Some times Android report a large delta time and just the next loop it's small than average, meaning an offset on the reading of realTime value.
with more detail:
How to limit framerate when using Android's GLSurfaceView.RENDERMODE_CONTINUOUSLY?
System.currentTimeMillis vs System.nanoTime
Does the method System.currentTimeMillis() really return the current time?

Related

Animating things framerate independent

I want to animate some text thats in an arraylist that gets changed often but I can't figure out how to animate it on the Y-Axis as it needs to move up and down and I've only set it up for obj.renderY += 10 * deltaTime but I need it to smoothly animate to the position wanted without overcomplciating it.
The current setup for animating the Y-Axis of the text is obj.renderY = (obj.renderY * (speed - 1) + offset) / speed and this is frame dependent and I haven't figured out how I would implement deltaTime into it properly most of the times I've tried it just breaks it. This current setup I have animates it to the position I want it to be on the Y-Axis even if its above or below the wanted position.
The offset is just equal to 2 + count * (fontHeight + 1) I don't know if that would help but sure I'll include it anyway. Thanks for taking your time and reading this post.
Example of trying to animate the texts movement:
float speed = 14;
obj.renderY = (obj.renderY * (speed - 1) + offset) / speed
The class that is used to get deltaTime (Updates every frame):
public class Time {
public static float deltaTime = 0;
private static long lastTime = System.nanoTime();
public static void update() {
long currentTime = System.nanoTime();
deltaTime = (currentTime - lastTime) / 1000000000.0F;
lastTime = currentTime;
}
}
Use javax.swing.Timer. It was literally built to solve this exact problem.
Timer(int delay, ActionListener listener)
delay - Place the amount of time you want the timer to wait before kicking things off. Please note - this does NOT mean the amount of time between each task, only the amount of time before starting each task.
listener - Place your actual task here.
Then, all you need to do is use the start() method, and that should be it. You can configure the timer in other ways, but that is the basics.
EDIT - I imagine that many people who are asking this question are game developers trying to make some part of their game run at 60 frames per second.
You can use a timer, but you might be better off using something from a game engine instead.
In short, you probably want something more feature rich than a simple timer. Timers are effective, but they can be hard to manage, and may not kick off at the exact frame that you want them to, leading to issues. Timers are meant to be a simple tool to make kicking off a task at a certain frequency easier. But it's rarely as simple as that when making a game.
I would discourage you from using this timer for anything other than a basic repetitive task that only needs to start and stop after a certain event. If you want something with precision, stick to using the tools found in some of your game engines. They specialize in getting certain actions to kick off at the exact times you want them to.

Simple way to use delta time to make movement smooth

This is a novice question about using delta time to move a sprite across the screen.
Also, I'm looking for advice as to whether or not delta time is even needed in this case...
Here is how I'm calculating delta time:
currentTime = System.currentTimeMillis();
if (lastTime == 0) {
lastTime = currentTime;
deltaTime = 0;
} else {
deltaTime = currentTime - lastTime;
lastTime = currentTime;
}
And I wanted to use this to somehow make a more fluid movement for objects in 2d space.
This is my current method to move an object up:
public void move() {
this.mPos.y -= mSpeed;
}
The thread constantly calls the move() method and it works well but the objects are slightly jittery across the screen. Any tips on how to incorporate delta time into this move() method? I'm trying to set a maximum speed of 10.
The position shouldn't move by the velocity -- the units aren't even the same! If you want to get a position out of a velocity, you need to multiply it by something with units of time (such as your deltaTime).
I imagine that your deltaTime is going to be quite small, so this should smooth the movement as well since the sprite will be moving more slowly. You'll probably need a higher velocity (or smaller position range) than what you're currently using though. If multiplying your velocity by deltaType doesn't get the results you want, I'd try adding a scaling factor and adjusting it around to see the difference it makes.

Moving objects smoothly, bad perfomance

I just finished developing my mini-game on Android and I got some questions about perfomance and generally "how to": If I have 25+ objects on the creeen (just a polygon with 7-8 angles) its starts to lag hard and CPU usage is very high (15-20% without colision detection, up to 50% with collision detection on samsung note 10.1 tablet).
So I have ~25 polygons (asteroids) and they are always "flying". So to move them I make a Timer, right? On TimerTask I got something like this
public void move() {
translate[1] += speed[1];
translate[0] += speed[0];
updateTranslateMatrix(); // updating translate matrix and then send it into vertex shader
updateAABBCoords(); // update coordinates of Axis-aligned bounding box
updateCoordsByTranslate(); // update coordinates of verticles (to be able to define exact collision (with bullets and starship))
}
Is there something unnecessary in this method?
Also I want to ask if it is OK to run this timer every 17 ms? Or 17 ms is too often? I feel smoothness of movement only at 17 ms, may be I am doing it wrong? And same Timer interval I got on starship/bullets movement and on Collision detection.
Help me, please. I feel like missing something huge and fundamental, because 50% CPU on note 10.1 in that simple Asteroids game is not normal.
One key issue, I believe, is that you are assigning an individual Timer to every object instead of employing a general purpose game loop. A vast majority of games use a game loop which runs continuously and can be split, typically, into two components: Update and Render.
An article on basic game loop design for Java/Android
An answer to a relevant question on game loop design on gamedev.stackexchange.com
When using a game loop you can not guarantee being able to update exactly every 17ms or some other arbitrary duration. Instead, the Update and Render methods receive a DeltaTime parameter which is the time since the last frame.
This is then used when, for example, getting new object positions by multiplying it with the object's velocity. Doing so allows for smooth interpolation of position and ensures that object speed is not affected by CPU speed.

My java game runs in slow motion on different computers

I am developing a game, and just wanted to test it on a different computer to check if the resolutions are ok and all that stuff but noticed one big problem, the game runs in slow motion for some reason... Not laggy, but slow motion..
My game loop is a temporary:
while(gameisRunnin){
doStuff();
Thread.sleep(1000/60);
But after the test, I've tried to check how much time does it take to do the doStuff(); code and I tested it like this:
while(gameisRunnin){
long startT = System.currentTimeMillis();
doStuff();
long stopT = System.currentTimeMillis();
System.out.println(stopT-startT);
Thread.sleep(1000/60);
The result it gives me is 0, on both computers, (On the one I am developing the game which runs in the perfect speed, and on the pc that it runs in slow motion..
Also I tested it with nano time, it gives me like 50000-80000 on both computes too (pretty much same result.
Seriously what's up? Could a superman save me?
UPDATE:
Ok so when I run the game on the other computer NOT on full screen, it's runs fine, but when it is on full screen, it's slowmotion
Update:
Looks like I am the superhero here, I've set the displaymode the refresh rate to unknown, I guess that was the whole problem...
You've to use something what is usually called "delta time". Basically it means, that you measure how long it takes to do one iteration of the game loop and then use this number for all the movements.
This is because of the different count of FPS on different computers. Instead of moving objects for just constant amount of pixels, you're defining speed and calculating the actual size of movement dynamically.
Short example:
public void gameLoop() {
long initialTime = System.nanoTime();
game.redraw();
game.update(System.nanoTime() - initialTime);
}
// inside the class Game
public void update(long deltaTime) {
someObject.moveToRight(deltaTime * speed);
}
The answer is that the refresh rate of the game wasn't supported by the monitor, changing the refresh-rate from 60 to DisplayMode.REFRESH_RATE_UNKNOWN fixes the slowmotion problem.
Read this article: click here
Also, as a side note, use System.nanoTime() because System.getTimeMillis() isn't as accurate.

Make an image move across the screen at the correct speed for all displays

I have a top down shooter using the paint method and I would like for it to work on all displays. It works by getting the resolution and dividing the x and y by 40 to separate it all up into squares.
My method of making the bullets move is by having a thread and a move method.
public void move(){
x += dx;
y += dy;
}
But if the persons computer is smaller, the bullet would move across the screen quicker. How can I get it to move at slower on smaller screens and faster on bigger screens?
Thank you for any suggestions.
What do you actually mean by slower? Do you mean as in the total time (measured in seconds) for the bullet to move across the screen is different in different devices?
Assuming that you did all calculation correctly as you described, I think you forgot one factor: different devices have different computing speed (and may be screen update speed also), so a "tick" in one device might be longer or shorted than some other. So when you call move, you should calculate how much time has passed from that last time moved() was called, and then you would calculate dx and dy based on it. Hope this make sense
I think you're forgetting not every computer runs at the same speed, if you've got this looping as fast as it can it will run very different on every computer. I suggest implementing delta scaling, this consists of timing the last frame, say you want 60fps, that means it needs to be 16 milliseconds, so take the time and divide it such as:
int lastframe = getFrameTime();
float scaler = lastFrame/(1000f/targetFrameRate)
then multiply all movements to this scale. such as:
public void move() {
x += dx * scaler;
y += dy * scaler;
}
A also see what you mean with different screen sizes being faster, this is because of the pixel density, to get this you will have to get the screen physical dimensions along with the resolution. For example if your screen is 20mm wide and its 1280x720, it's 20/1280 , this gives you the fact that each pixel is 0.015mm wide. You can then use the above scalar technique to scale them to move a physical world speed.

Categories