I've been working on a little proof of concept game that has a rolling environment in the background (2D). I have a custom class object called roadTile, which basically is a 200px tall block with a picture to paint on and some physics. I'm storing the tiles in a LinkedList 5 at a time. I have a main loop that is responsible for moving everything and checking for collisions. The loop is supposed to be performed every 50ms (controlled by a timer) and it keeps the rate fixed by measuring the length of the last run and then taking deducting it from the sleep-time.
This usually runs fine and the loops run in less than a millisecond, but when I start the program, it "chokes" after the first 2-7 times. I removed the old tile and put a new one on the bottom of the list. On calling the add (new roadTile()), the program halts for 20-400ms which is a millenium in computer time, and to top this off, the behavior isn't consistent. Sometimes it works fine some times not.
I'm pretty clueless how to eliminate this, any thoughts?
Make sure that you cache everything before you start working with graphics. This might be the cause of your delay.
Related
With the languages and libraries I've worked so far, there was always an option to sync the main loop of the program (a game or anything with an always changing context) to the current display's refresh rate. So I had the option to either switch on VSYNC or just let the loop execute as many times per second as it could. I'm referring to SDL2, OpenGL 3.0 with GLFW, the HTML5 canvas etc.
I'm looking for something similar on Android now in OpenGL ES 2.0, but so far all the example code I can find simply uses a variation of sleep and set the framerate to 60 or 30. So they basically count the amount of time passed since the last iteration, and only advance further and call the requestRender() function if a given amount of time has passed (0.016 ms in case of 60 frames per second etc.).
I'm simply wondering if there's a better option than this or not. I'm just concerned that not every phone has the same screen refresh rate, so hard coding any amount doesn't seem to be a desired method. As far as I understand it is not that simple to figure out the given phone's refresh rate, or at least it is not possible with "pure" Java and OpenGL.
What you need to do is match the display's frame rate, and advance game state according to how much time has elapsed since the previous frame. There are two ways to go about this:
Stuff the BufferQueue full and rely on the "swap buffers" back-pressure.
This is very easy to implement: just swap buffers as fast as you can. In early versions of Android this could actually result in a penalty where SurfaceView#lockCanvas() would put you to sleep for 100ms. Now it's paced by the BufferQueue, and the BufferQueue is emptied as quickly as SurfaceFlinger is able.
Use Choreographer.
Choreographer allows you to set a callback that fires on the next VSYNC. The actual VSYNC time is passed in as an argument. So even if your app doesn't wake up right away, you still have an accurate picture of when the display refresh period began. Using this value, rather than the current time, yields a consistent time source for your game state update logic.
source: https://source.android.com/devices/graphics/arch-gameloops
I am creating a voxel game in Java. Currently, I am using perlin noise to generate data for 3d chunks (16x16x16 short arrays) which are contained in a HashMap. This all works correctly. When the player moves, I want to render the chunks near the player (right now, 5 chunks in any direction). If a chunk does not exist, it should generate it.
The problem is that it takes about half a second to generate a chunk so when the player moves out of the generated area, the game loop freezes for a couple seconds while it generates the necessary chunks and then resumes.
I am using lwjgl for OpenGL and my game loop looks something like this:
while (!Display.isCloseRequested()){
update(); //my update method
render(); //my render method
Display.update(); //refresh the screen
Display.sync(60); //sync to 60 fps
}
I have tried, unsuccessfully, to use a second thread to generate data while updating and rendering but I could not figure out how to do it without freezing the game loop. I think there should be a way to queue chunks to generate in a second thread and then run that thread in short bursts but I have little to no experience with multithreading in Java so any help with that would be appreciated.
If the player can see the five chunks around him, you can maybe generate the chunks six rows away before he enters one direction. This way you have done the work early enough and you can display the chunks directly.
This task of generating the chunks you can do in a separate thread. It doesn't have to be called in the game-loop. You have to invoke the generater-thread before entering the game-loop.
I'd have a background thread that's notified when the player moves, then pregenerates chunks adjacent to the where the player moved. It's backed by a priority queue so that backlogs of never-visited cells aren't at the top of the queue, and old queue entries are removed once they're a certain distance from the player.
The key to leveraging threading is that you're generating the chunks before the player moves there, and taking down time in movements to generate chunks, and possibly unneeded chunks.
And the big caveat: if you offload all generation to that thread, you're going to need to use Futures so you always get back a generated chunk.
Okay, I solved my problem using only one thread. I created a TaskManager which was responsible for holding an arraylist of tasks to be done. So every time I needed to generate a chunk, I would pass a task object that contained information to actually perform the task. Then, every update, I would call TaskManager.next() which would perform the next task.
Now, instead of generating 49 new chunks in one update which froze the framerate, it generates one chunk per update until they are all generated.
Let's imagine a simple Java program, where there are 5 2D marbles moving around in a circle in a fixed order. You can control the speed of every marble keeping in mind that slower marble is blocking the marble moving faster (they can't overtake). They all move in one direction in a circle. What would be the best way to program this? The idea is to assign a separate thread to every marble, that's actually one of the requirements.
Then I create five threads, synchronize the "move" method on some object common to all threads. The next step is checking whether I can move the marble forward, if there is some free space. So before I move, I check if there is free space and then take action. Is it necessary or at least a good idea to use wait() and notify() mechanism here?
Thanks for help.
Well, I'm not going to code your homework for you, but here is a high level look at it.
You will need each marble to update it's position at regular intervals, so some type of looping is required. This loop is commonly known as a game loop. Here is a discussion of various types of them, going from simple to complex. http://www.java-gaming.org/index.php?topic=24220.0 For your project, something simply may be sufficient, but I don't know the requirements of it.
Each time a marble tries to move, it must check to make sure it isn't being blocked. If you have the move method synchronized, as you mentioned, then only one marble should be able to move at a time, so that should avoid concurrency issues.
Except for using a Thread.sleep in your game loops, I don't see any reason for you to doing any waiting. Java has a synchronize keyword, which can be used to lock the shared object that you mentioned using for movement, to avoid the concurrency issues. So I don't believe wait and notify are necessary.
Just my thoughts, I hope it is of some help.
To give some background information, I'm currently working on a Java coded pinball game. I'm keeping it in an MVC design model. It has a fairly realistic physics system that allows it to work collisions, gravity, friction etc. The system runs on a 20 FPS system right now.
The problem I'm having is that the physics loop that checks for collisions in the system works by running a method that using the current velocity of the ball calculates the time until the next collision. The most effective way for this to work would obviously be to keep running the check to account for the movement of the ball between checks to get it as accurate as possible, and if the time until collision is less than the time until the next check, then carry out the collision.
However, right now the system I am working with can only run the loop 20 times per second, which does not provide as accurate results as I would like, particularly during times of high acceleration, such as at ball launch.
The timer loop that I use is in the controller section of the MVC, and places a call to the physics section, located within the model. I can pass in the time remaining at the time the method is called in the controller, which the physics system can use, however I don't know how to run the loop multiple times while still tracking the remaining time before the next screen refresh?
Ideally I would like to run this at least 10 times per screen refresh. If anybody needs any more information please just ask.
Thanks for any help.
So the actual problem is that you do not know when the the collision will happen and when the next frame update is?
Shouldnt these be seperate running tasks? One thread that manages the collision detection and one that does the updating? each thread can run on its own interval (Timer.addTask(...)) and they should propebly be synchronized so colission/location updates are not performed when the render thread is executed.
Hope this answers your question.
Regards, Rob.
I'm making a Java game and I'm stuck on how to do timing easily. I know there's the delta time thing, but that would mean that I have to insert that delta variable in almost every movement/update function?
I was wondering if I can just time the main While loop of the game so it runs/loops every 50 miliseconds, rather then as fast as it can.
Changes in position are functions of time, so it makes sense to have to pass the time delta into most functions that update game state. It's the natural thing to do; I wouldn't be apprehensive of doing so.
While it is possible to insert delays every frame (and you almost certainly want to do so, as there's no point in having a game run at 1000 fps), it is usually detrimental to have your update logic assume that each frame will have taken a preset amount of time. Doing so results in choppiness when one frame happens to take longer than others.
To give your game a certain framerate, the general approach for each frame is as follows:
Record the current time as startTime.
Do the state updates.
Redraw.
Record the current time as endTime.
Sleep for (1 / framerate) - (endTime - startTime)