Understanding Interpolation - android

I have been reading up on game loops and am having a hard time understanding the concept of interpolation. From what I seen so far, a high level game loop design should look something like the sample below.
ASSUME WE WANT OUR LOOP TO TAKE 50 TICKS
while(true){
beginTime = System.currentTimeMillis();
update();
render();
cycleTime = System.currentTimeMillis() - beginTime;
//if processing is quicker than we need, let the thread take a nap
if(cycleTime < 50)
Thread.sleep(cycleTime);
)
//if processing time is taking too long, update until we are caught up
if(cycleTime > 50){
update();
//handle max update loops here...
}
}
Lets assume that update() and render() both take only 1 tick to complete, leaving us with 49 ticks to sleep. While this is great for our target tick rate, it still results in a 'twitchy' animation due to so much sleep time. To adjust for this, instead of sleeping, I would assume that some kind of rendering should be going on within the first if condition. Most code samples I have found simply pass an interpolated value into the render method like this...
while(true){
beginTime = System.currentTimeMillis();
update();
render(interpolationValue);
cycleTime = System.currentTimeMillis() - beginTime;
//if processing is quicker than we need, let the thread take a nap
if(cycleTime < 50)
Thread.sleep(cycleTime);
)
//if processing time is taking too long, update until we are caught up
if(cycleTime > 50){
update();
//handle max update loops here...
}
interpolationValue = calculateSomeRenderValue();
}
I just don't see how this can work due to the 49 tick sleep time? If anyone knows of an article or sample I can check out please let me know as I am not really sure what the best approach to interpolation is...

I know its a bit late, but hopefully this article will help
http://gameprogrammingpatterns.com/game-loop.html
It explains game time scheduling very well. I think the main reason you are a bit confused is because of passing the render function the current elapsed time. Oh course this depending on which system you are using but conventionally the render doesn't modify the Scene in any way, it only draws it, therefore it doesn't need to know how much time has passed.
However the update call modifies the objects in the scene, and in order to keep them in time (e.g. playing animations, Lerps ect...) then the update function needs to know how much time has passed either globally, or since the last update.
Anyway no point me going to fair into it.... that article is very useful.
Hope this helps

Related

Device goes black and Launch timeout expires

Since I am new to android programming, I am not sure how to write code efficiently hence the reason for this question. I am creating an app. A basic app in which the app generates 10 random math questions and evaluates it from left to right (ignoring orders of operations). E.g. 3+5/2 should equal 4 instead of 5.5.
I am getting the error Launch timeout has expired. I have researched this and found out that its because the main thread is doing too much work. How do I overcome this? My app first does alot randomizing integers, could that be the case?
This is the code. It is pretty long.
P.S. in the display method, i hrdcoded it to display the first elements just to see if it will display.
public void initAnswers(String[] questionToBeLooped){
for(int i =0; i < questionToBeLooped.length; i++){
if(mathOperations.length == 2){
runningTotal = evaluateAnswerTwoOperations(mathOperations[0], mathNumbersInIntFormat.get(0), mathNumbersInIntFormat.get(1));
}else{
int operationsCounter =0;
int numbersCounter =1;
runningTotal = mathNumbersInIntFormat.get(0);
while(mathOperations[operationsCounter] != "="){
runningTotal = evaluateAnswerTwoOperations(mathOperations[0],runningTotal,mathNumbersInIntFormat.get(numbersCounter));
}
}
answers[i] = runningTotal;
}
}
Could someone tell me how to write this efficiently and also can you provide some tips to generate fluent and efficient apps.
Not sure what in your code is the cause, but you should offload the heavy work into an AsyncTask. AsyncTask will allow you to execute code in a background thread via doInBackground and callback to the UI thread via onPostExecute. The heavy work you are doing is probably something around the looping constructs you have.
Keep in mind that you cannot modify the UI from the background, so if you need to update UI, wait until the heavy work is finished and do it in onPostExecute.
See the docs here on AsyncTask.
Also worth noting that AsyncTask has a lot of flaws, but since you are new - it is where I would recommend to start.

How can I make an object move across my screen gradually using a loop in Lua and Corona Labs SDK

I'm making a game that has obstacles which the player must jump over. I'm using the Corona Labs Simulator to run it but every time I do either the obstacle gets half way across the screen instantly and stops or the whole thing just crashes. Here is my code:
function obstacles()
loop = 2000
while loop > 0 do
obstacle:translate( -1, 0 )
if obstacle.x > 0 then
loop = loop - 1
else
loop = 2000
obstacle:translate( display.contentWidth, 0 )
end
end
end
Any help much appreciated.
Its important to understand that Corona SDK is an event driven system. There really isn't a game loop. Code executes so fast you can't use structures like loops to move things.
As mentioned above, the transition library (transition.to for instance) can move an object over time.
The closest thing to a game loop is to create a function and attach it to the Runtime object using the "enterFrame" event. Every frame (either 30 times per second or 60 times per second), this function will be called. It's not going to be precisely 30 or 60 times per second because it make take too much time doing other work to give you the full frame rate. If you want to use an enterFrame listener:
local function doSomethingEachFrame( event )
-- put code here you want to execute over time.
-- just remember it fires a lot...
end
Runtime:addEventListener( "enterFrame", doSomethingEachFrame )
If you need to stop it, then you would do:
Runtime:removeEventListener( "enterFrame", doSomethingEachFrame )
Corona SDK provides tools to do exactly that. Rather than using a loop, use transition library:
transition.to(target, params)
where target is your obstacle object, and in params, you can specify x position, time etc.
There can be a few sources of weirdness regarding where things appear on-screen. I'd put obstacle at (0,0) with no movement at all and make sure I understand both the coordinate system of the parent, and the anchorX and anchorY of obstacle before trying to animate it.
I assume there's other code outside the block you've included, but I think you can make the movement logic simpler, and you'll thank yourself later (this isn't perfect, but you get the idea):
-- set initial position
obstacle.x = display.contentWidth
-- define per-frame movement logic
local moveObstacle = function(event)
obstacle.x = obstacle.x - 1
if obstacle.x < 0 then
obstacle.x = display.contentWidth
end
end
-- run that logic once every frame
Runtime:addEventListener("enterFrame", moveObstacle)

Do after specific time, Android Runnable

Ive got an app with a class that implements Runnable. Where a thread is started and the run() methid overridden. This runs my graphics.
1.st question : how often is the run() called upon? i havent set a time for this so it must be a default value?
2.nd question : i want stuff to be done after a certain amount of time (2min,5min,10min) etc. What would be the best way to go about doing this, i was thinking about using an int as an counter and once it hits a specific value does what i want.
1.st question : how often is the run() called upon? i havent set a time for this so it must be a default value?
The run() method in your Thread is called when you call it eg. yourThread.start();
2.nd question : i want stuff to be done after a certain amount of time (2min,5min,10min) etc. What would be the best way to go about doing this, i was thinking about using an int as an counter and once it hits a specific value does what i want.
There are to options. Either you could call Thread.sleep() method (NB: Never do this in your UI thread).
Or you can do it the way you described above. So in your run() method you would have a while() loop and check on every iteration if the difference of the lastUpdate and the current time in milli seconds is bigger than the wanted period eg. 2 min, 5 min or 10 min.
I hope this helps.
Regarding question 2 - use ScheduledExecutor
1.st question : how often is the run() called upon?
You can find out for yourself, put this at the start of your Runnable:
Log.v("Running Runnable", System.currentTimeMillis() + "");
2.nd question : i want stuff to be done after a certain amount of time (2min,5min,10min) etc.
Extend a HandlerThread (it initializes the Looper for you!), add a Handler as a class variable, and use the Handler's postDelayed() or postAtTime() methods.
The exact amount of time in between calls to run() depends on the processor. The time between each call is the sort of thing that's really visible by the nanosecond. If you're trying to create a timer, I'd recommend using System.currentTimeMillis(), calling it in the run() method, and once the difference is greater than or equal to 1000 milliseconds, the actual timer decrements by one. This will keep track of seconds, and you can use it as a base for minutes and generating other events at specific times.

How to rotate an object during a specific time in OpenGL ES for Android?

In OpenGL ES for Android I have an object that I want to rotate with gl.glRotate. But I want this rotation to happen during n seconds, not immediately. How can I implement this? I want this to happen during n seconds so that the user can see the rotation.
How quickly is your object rendered on the View. Suppose it takes time t for one update, then the amount by which you should rotate your object will be (t/n)*r, r being the total amount of rotation you want in n seconds. So in a total of n seconds, the effective rotation will be r.
use System.currentTimeMillis(); to get time passed .
int seconds=5;//rotate in 5 seconds
long rotatestarted;
void StartRotate()
{
rotatestarted=System.currentTimeMillis();
}
void Render()
{
if(rotatestarted+seconds*1000<System.currentTimeMillis()){
DoRotate();
}
}
OpenGL and OpenGL ES do not provide such functionality. All they provide is ways do draw and transform things now, without any consideration of time.
What you need is some system, your own or some framework/library/engine that will handle time, and states relative to it.
In this regard SteveL answer is correct, you have to handle this by yourself.

Android synchronizing?

I am not fully understanding what the synchronization block is doing nor why it is necessary.
Can someone explain in a "synchronizing for dummies" kind of way?
In a book I am reading, the author tells me "The synchronization is necessary, since the members we manipulate within the
synchronized block could be manipulated in the onPause() method on the UI thread."
He creates an Object named stateChanged and instantiates it as a new object.
Then, in the synchronization block he uses the stateChanged object as the argument.
This whole thing is throwing me off and I do not like to move on until I have a pretty good understanding of what is going on.
The classic example is: Imagine you have two threads of operation, and both of them reference the same method:
public void addToGlobalVar(int y) {
int x = globalVar; //what if a thread stops right after this line?
x += y;
globalVar = y;
}
where globalVar is some other predefined number that this method can interact with and set. Lets say globalVar is 50.
Threads get computing time on a somewhat arbitrary basis, so you never fully know the precise nanosecond one stops and the other gets CPU time.
In this example, if you launched an AsyncTask in addition to the UI thread, and both at some point use addToGlobalVar(10), what can happen is that one thread might be interrupted at line 2 of that code block. If the other thread goes through while that one is sleeping, it will successfully set globalVar to 60. But when the other one wakes up, it still thinks x = 50, and its going to then set it to 60. So in essence you just made 50+10+10 = 60. Hopefully you can see how this becomes a problem.
You can fix this simple example by making the calculation atomic (skip declaring x, 1 line, all calcs done) or if the logic wasn't able to be condensed to 1 line, you make a block of code atomic by using synchronized.
The book to read is Java Concurrency in Practice.
You should really just segregate this idea from Android, although your code is going to be running on Dalvik this is a Java concept. Not an Android one.
The synchronized block takes an object as a parameter, any object, and when flow enters the body of the synchronized block, any other thread that runs in to a synchronized block with the same instance (object) as the parameter has to wait for the previous one to complete. That's a very basic description.
This is an entire sub-field of computer science and without serious study you will probably not understand it.
You have to fully understand it before you use it. It is standard android synchronization using object-oriented monitors. You have to understand it to write multi-threaded programs, however it is somehow dated (better use java.util.concurrent for anything thread/synchronisation related instead).
Anyhow - you need to know what it is about - read the related java tutorial part:
http://download.oracle.com/javase/tutorial/essential/concurrency/sync.html

Categories

Resources