How to capture milliseconds value with millis() using Processing? - java

I'm currently working with Processing. I would like to execute a function 4 seconds after its call. I tried using millis() by taking a value at a certain time and comparing. But when I write:
final int m = millis();
The value of m changes at the same time millis() changes.
How can I capture a constant value of millis()?
PS. I've tried using final and static.

You need to scope the variable at the sketch level, outside of the draw() function so that you aren't recreating it every time. You also need to compare the variable to the current time. Something like this:
int startTime;
void setup(){
startTime = millis();
}
void draw(){
int currentTime = millis();
if(currentTime > startTime + 5000){
background(255, 0, 0);
}
}
I'd also recommend doing a search on Stack Overflow for the millis() function.

Related

how to run a code 60 times per second in java

if I don't control the number of times per second my code executes, when I add a line, the program varies and I have to adjust the constants again. (translated by Google)
My code running out of control:
public builder(){
while(true)
stepEvent();
}
private void stepEvent() {
setOfActions();
repaint();
}
This is just one way to do it(it's very long but VERY precise - I recommend it for game development). In this case I'm using the run() method from the Runnable interface to execute the code.
public void run(){
long lastTime = System.nanoTime();
final double ns = 1000000000.0 / 60.0;
double delta = 0;
while(true){
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1){
the code you want to be executed
delta--;
}
}
}
Explanation Line by Line:
Basically, I store the current time in nanoseconds in lastTime. Then in ns I store 1/60th of a second in nanoseconds and create a variable delta.
After this, I go inside the infinite while loop(it doesn't have to be infinite) and store the current time in nanoseconds once again in now. This is to take into account the amount of time that took the computer to go from the lastTime declaration line to the while loop line.
After doing all this, I add to delta the difference of now and lastTime divided by the 1/60th of a second(ns) I mentioned. This means that every time delta is equal to 1, 1/60th of a second will have passed.
Right after this, I make lastTime be the same as now. In the while loop that comes afterwards I check if delta is equal or greater than 1 and then in there you should put all the code you want to be executed 60 times per second. Don't forget to substract 1 from delta so it doesn't loop endlessly.
Analyze the code thoroughly and see if you can understand it. If you can't, I'll clarify further. I insist that this is just one possible way to do it, but there are many more ways.
Note: In some cases, you will never even need delta, but it is very helpful for some purposes.
Credit for the code: Most of this code(at least where I got it & learned it) is extracted from TheCherno's Game Programming Series
Have a great day!
import java.util.Timer;
import java.util.TimerTask;
public class HelloWorld {
public static void main(String []args) {
// number of ms in 1/60 of a second
// there will be some rounding error here,
// not sure if that's acceptable for your use case
int ms = 1000 / 60;
Timer timer = new Timer();
timer.schedule(new SayHello(), 0, ms);
}
}
class SayHello extends TimerTask {
public void run() {
System.out.println("Hello World!");
}
}
Basically, you have to execute your stepEvent every 17 ms.
With the assumption you want to run sequentially, you could stop the execution during a defined period by using Thread.sleep(millis , nanos). In this case, we will stop the thread 17ms minus the stepEvent execution time (think to add condition to avoid negative value in sleep function)
long startedTime;
for(;;){
startedTime = System.currentTimeMillis();
stepEvent();
Thread.sleep(17 - System.currentTimeMillis() + startedTime);
}
Otherwise you can use the ScheduledExecutorService which allows you to schedule code to run periodically at fixed time intervals (or after a specified delay). In this case, you can execute your step at a fixed rate every 17ms.
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.scheduleAtFixedRate(YourClass::stepEvent, 0, 17, TimeUnit.MILLISECONDS);
You can also configure to use severals thread with Executors.newScheduledThreadPool

Can't set delay in libgdx

I want to remove an index from an array after some time, I want it to fall, then delete it.
private final int gravity = 4;
private long lifeTime=0;
private long delay = 20000L;
public void objGravity() {
while (array.get(array.size - 1).y > 0)
array.get(array.size - 1).y -= gravity;
lifeTime = System.currentTimeMillis();
lifeTime += Gdx.graphics.getDeltaTime();
if (lifeTime > delay) {
array.removeIndex(array.size - 1);
lifeTime = 0;
}
}
The object gets removed from array immediately as if there's no delay whatsoever, so it doesn't appear to be falling down on the screen.
Update
I removed time and so on. I added a counter to count how many objects need to be removed and then I do a loop that removes array.size-1 as long as counter>0.
Not sure if it's the best approach, seems like a hack but I don't want to do threads on old mobile phones. If you have a better idea please share
Don't fire threads inside the render method, it's not safe, can cause thread leaks, a lot of other problems and will be harder to maintain your code, to handle time use a variable adding delta time every time render is called, when this variable is superior a 1.0f means that one second has passed, your code would be something like this:
private float timeSeconds = 0f;
private float period = 1f;
public void render() {
//Execute handleEvent each 1 second
timeSeconds +=Gdx.graphics.getRawDeltaTime();
if(timeSeconds > period){
timeSeconds-=period;
handleEvent();
}
[...]
}
public void handleEvent() {
[...]
}
To keep organized i personally have an array on my main game class that holds all my timed events and process everything on the render cycle.

How to make a countdown?

I'm trying to create a countdown. I don't see how exactly I can make a countdown. Can anyone help?
The code does what you tell it. You say in onStart:
end.add(Calendar.MINUTE, 4);
end.add(Calendar.SECOND, 5);
which tells the system you want a countdown starting at 4 minutes and 4 seconds. Instead, do:
end.add(Calendar.SECOND, 45);
EDIT
Took a while to understand what you meant. First, go to github and copy TickTockView into your own project. Remove the dependency to the original project. Open the file and in onDraw, change:
if (mCircleDuration == DURATION_TOTAL && mStartTime != null) {
long totalTime = mEndTime.getTimeInMillis() - mStartTime.getTimeInMillis();
float percentage = (((float) mTimeRemaining) / ((float) totalTime));
angle = 360f * percentage;
}
to:
if (mCircleDuration == DURATION_TOTAL && mStartTime != null) {
long totalTime = mEndTime.getTimeInMillis() - mStartTime.getTimeInMillis();
float percentage = (((float) mTimeRemaining) / ((float) 45000));//45000(ms) = 45 seconds
angle = 360f * percentage;
}
In your xml file where the circle is defined, add:
app:tickCircleDuration="total_time"
And by doing that, you only need to change totalTime in onDraw in the TickTockView. Remember to update the package name in the XML file to point to the place you saved the file, not the original project.
For reference, this is the file you should copy
The good way is to use CountDownTimer class provided by Android for downward counting in time. I have recently used it in my game and is simple in use. First you
CountDownTimer timer = new CountDownTimer(45000, 1000) {
// 45000 milliseconds countdown and 1000 milliseconds decrement at each tick.
public void onTick(long millisUntilFinished) {
//you can change your UI here based on time
}
public void onFinish() {
// you can define something to happen when timer ends.
}
};
timer.start();
Change the below code into
Calendar end = Calendar.getInstance();
end.add(Calendar.MINUTE, 4);
end.add(Calendar.SECOND, 5);
into
Calendar end = Calendar.getInstance();
end.add(Calendar.MINUTE, 0);//O minute
end.add(Calendar.SECOND, 45);//45 second

Calculating time passed in libgdx with getDeltaTime()

i am trying to calculate the time passed in my libGDX application like this
float timeSpent= 0;
public void render(){
timeSpent = timeSpent + Gdx.graphics.getDeltaTime();
}
by the above code i feel like the time is almost passing double the normal rate
but if i get delta time directly from java's nano time method like this
float prevTime;
float timeSpent = 0;
public void show(){
prevTime = System.nanoTime();
}
public void render(){
float p = System.nanoTime();
timeSpent += (p-prevTime)/1000000000f;
prevTime = p;
}
it seems to work fine, i know that libgdx also get delta time from subtracting
nano time method.
i am not able to figure out what am i doing wrong in the first method.
thank you
You can calculate the passed time from the start of your application by simply saving a date when it starts, and just subtract it from the current date. No need to accumulate the deltas in each frame.
You can further simplify the code by using TimeUtils:
// save at start
long start = TimeUtils.millis();
// query whenever you want
long diffInMillis = TimeUtils.timeSinceMillis(startTime);

StackOverflowError using Recursion

I'm supposed to be comparing a Recursive and a Non-Recursive function to see which one is quicker for a class project. The professor also wants us to time the iterations in milliseconds when the iterator is equal to 10,100,1000, etc. I got it all to work but was having loads of trouble in C++ getting the timer, so I switched to Java as it's much much easier to get millisecond output.
But now when I try to use any number over 8,000 I get a big fat stack overflow error from the Recursive algorithm. Can anyone give me any insight?
Bonus: I also can't figure out how to do the timer in the Recursive function like I did in the Non-Recursive. How would I approach this?
public class comparingTimes {
public static void main(String[] args) {
double num = 10000;
double result;
nonRec(num);
result = rec(num);
System.out.printf("Rec %.0f",(result));
}
public static void nonRec(double num)
{
double resultNum = 1;
double total = 0;
long startTime = System.currentTimeMillis();
long endTime;
for (double i = 1; i < num; i++)
{
total += i * (i+1);
if (i == resultNum)
{
endTime = System.currentTimeMillis();
System.out.printf("Total execution time: %f seconds - num = %.0f%n", (endTime - startTime)/1000.0, i);
resultNum *= 10;
}
}
System.out.printf("NonRec: %.0f%n", total);
}
public static double rec(double num)
{
if (num == 0)
return 0;
else
return num * (num-1) + rec(num-1);
}
}
The ideal use case for recursion is when you reduce the "search space" massively on each recursion level. For example, consider a binary search where each recursion level halves the remaining search space.
Your particular problem is that you're trying to do 8000 levels of recursion since each level simply decrements the value. That's going to require a fairly large chunk of stack space.
You can look into increasing the stack size for your JVM with the -ss or -oss options (depending on implementation, of course). But that will only buy you so much.
In terms of timing the whole recursive operation, I would simply store the time before the top-level call in main(), then compare that to the time after that top-level call returns, something like:
long startTime = System.currentTimeMillis();
result = rec(num);
long endTime = System.currentTimeMillis();
// Now calculate the elapsed time.
There's no need to try and do it within the recursive call itself.
If you want to do it at certain points within the recursive call, you can initialise a "global" counter variable (one outside the recursion itself, such as a class-level static variable) to 0 and have the recursive function increment it for every recursion level.
Then have it output the time deltas at the points you're interested in, such as when the variable is set to 10, 100, 1000 and so on.
Try increasing the stack size.
As for measuring time
public static void main(String[] args) {
double num = 10000;
double result;
long start = System.currentTimeMillis();
nonRec(num);
long finish = System.currentTimeMillis();
System.out.println("Time taken (non-recursive): " + (finish -start));
start = System.currentTimeMillis();
result = rec(num);
finish = System.currentTimeMillis();
System.out.println("Time taken (recursive): " + (finish -start));
System.out.printf("Rec %.0f",(result));
}

Categories