Switching between videos after certain time duration - java

I am working in Processing, using java. I'm trying to create a cctv type footage experience, where the viewer sees different camera footage flicked through based off of the amount of time that had passed since the program ran.
Currently, the first video plays perfectly fine. But then once that one stops, for some reason the second video never displays.
void draw(){
int timer = getAgeInSeconds();
if(timer <= 20){ // RESPONSIBLE FOR SWITCHING OUT MOVIES
if(movie1.available()){ // Refreshes frame. Can mofify with FrameRate()
//frameRate();
movie1.read();
image(movie1,0,0, width, height);
}
}
if(timer >= 21){
if(movie2.available()){
movie2.read();
image(movie2,0,0,width,height);
}
}
}
public int getAgeInSeconds(){ //FUNCTION FOR CALCULATING SECONDS FROM RUN TIME INSTEAD OF COMPUTER CLOCK
long nowMillis = System.currentTimeMillis();
int timer = (int)((nowMillis - this.createdMillis) /1000);
print("\n" + timer);
return(timer);
}

Related

Java StopWatch in ChessGame

I have two threads in my ChessGame and I want to implement time control:
Turn of first player: second_thread.stop(), first_thread.run();
counterOfSteps++;
Turn of second player: first_thread.stop(), second_thread.run();
counterOfSteps++;
I have founded many information about Timer but I need Threads.Second thread the same.
There is my code of first thread and it doesn't work because time isn't stopped (System.currentTimeMillis)
first = new Thread() {
#Override
public void run() {
final long time = System.currentTimeMillis();
final long duration = 10800000; //3 hours
while (true) {
try {
Thread.sleep(100);
if (counterOfSteps % 2 == 0) {
System.out.println("Time" + ((duration - (System.currentTimeMillis() - time)) / 1000) % 60);
}
} catch (InterruptedException ex) {
LOG.log(Level.SEVERE, "Unexpected interrupt", ex);
}
}
}
};
How to solve this problem?
Update:
I don't use .stop(). I wrote is for example how to realize.
I have founded many information about Timer but I need Threads.
No. If all you are trying to do is implement a chess clock, then you don't need threads for that. A Timer task that wakes up every second (or every 1/10 second) can;
look at whose turn it is (e.g., counterOfSteps % 2),
compute how much time that player has used, and
Update the appropriate text box in the GUI.
To compute how much time, it'll need to know three things;
What time it is now (e.g., System.currentTimeMillis()),
What time it was when the current turn started, and
How much time the player already had on the clock when the current turn started.
There is no way to pause the system clock (i.e., System.currentTimeMillis()), but that's not a problem. If you sample the clock at the start of each turn, then you can compute the duration of the current turn as System.currentTimeMillis() minus the start time.
I used this example for my quiz, i have 10sec do answer on question this timer decrease int t every 1sec, and set how many times left in some JLabel. You can make 2 object of Timer, first object for first player and second object for second player. You can stop timer when someone finish the move and start second timer...
int t=10
lb2=new JLabel(t);
tim=new Timer(1000,new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
if(t>0){
t--;
lb2.setText(String.valueOf(t));
}else{
tim.stop();
JOptionPane.showMessageDialog(null, "Time is up");
}
}
});
}

Pausing TimeUtils in libgdx

In my game I have objects that gets spawned regularly on a 0.45s basis. When spawned into the world, they'll get a copy of the nanoTime at that time. That way I can check with the current nanoTime to remove the object after a certain amount of time has passed.
Now the problem is when you pause the game. Because the nanoTime will, of course, keep going which will make the objects disappear directly after you get out of the pause screen (if the pause screen was up longer than the amount of time it takes to remove the object).
Is there a way to freeze the nanoTime or something like that when you enter the pause screen and resume from where it left when you exit so the objects won't disappear directly after you get out of the pause screen?
I would recommend changing the way you store your spawned objects. Rather than storing the time when they are added to the world, you should store how long they have left to live.
On each render frame libGDX provides you with a delta parameter to measure how long has elapsed since the last render time. You would decrement from the timeLeftToLive variable (or some other name) this delta value if the game is not paused.
The code below illustrates my point (just a dummy class):
class ObjectTimer {
private float timeToLive = 0; //How long left in seconds
public ObjectTimer(float timeToLive) {
this.timeToLive = timeToLive;
}
//This method would be called on every render
//if the game isn't currently paused
public void update() {
//Decrease time left by however much time it has lived for
this.timeToLive -= Gdx.graphics.getDeltaTime();
}
//Return if all the time has elapsed yet
//when true you can de-spawn the object
public boolean isFinished() {
return timeToLive <= 0;
}
}
Then you might have a loop in your main game that would do the updating something along the lines of:
//Do this if the game isn't paused
if (!paused) {
//For each of your sprites
for (MySprite sprite: spriteArray) {
//Update the time run for
sprite.getObjectTimer().update();
//Check if the sprite has used all its time
if (sprite.getObjectTimer().isFinished()) {
//Despawning code...
}
}
}

LibGDX stop time counter on pause

In LibGdx, is there a way to pause the delta time when user pause the screen/left apps temporary (such an incoming call)? Take for example, when displaying message is going to take 10 secs for user to read the message, normally, I would get the message displayed start time, do the calculation in render() to get the elapsed time (currentTime - MessageStartedTime), if elapsed time > 10secs, then close message, everything works correctly, right. Imaging this scenario, user is reading the message (let assume elapse time is 2 secs), an incoming call that took 20 secs, when the process is brought back to my apps, the elapsed time > 10 secs, and therefore the message will be removed even though the message is only displayed for 2 secs.
so, my question is, is there a master time counter that I can implement in my application for this kind of purposes? and what is the best way to implement it?
I have two game states, they are:
GAME_RUNNING
GAME_PAUSED
When pause() is called I set the state to GAME_PAUSED and when resume() is called I set the state to GAME_RUNNING.
And then when I run update() on my game I check this state and if it's paused I set delta to 0.
float deltaTime = game.state == GAME_PAUSED ? 0 : Gdx.graphics.getDeltaTime();
This means when all my game objects update, their changes are multipled by 0 and nothing changes. We can also add a condition and only update when deltaTime > 0.
If you have a timer, you'll be updating this timer somehow like:
public void update(World world, float delta) {
frameTimer += delta;
if( frameTimer >= rate / 1000) {
fireAtEnemy(world);
frameTimer = 0;
}
}
Because delta is now 0 the timer will not increase and not increase until the game state it back to GAME_RUNNING after resume().
Additionally, you can add an extra state called something like GAME_RUNNING_FAST and when this state is set you can multiply the deltaTime by 2 for example. If you have all your updates relative to the deltaTime then your entire game will run at double speed. If that's something you'd desire.
private long pauseTime = 0;
private long pauseDelay = 0;
#Override
public void pause() {
pauseTime = System.nanoTime();
}
#Override
public void resume() {
pauseDelay = System.nanoTime() - pauseTime;
pauseTime = 0;
}
And in your render method you just do long displayTime = delta - pauseDelay; pauseDelay = 0;

Displaying JLabel movement

I am attempting to create a simple animation in which a series of bubble rotate around a centre point. I have one version of animation where the bubbles spread from the centrepoint before they begin to rotate, which works fine, but as soon as I click one of the images (which sparks the animation) the screen freezes for a moment and then the bubbles appear in their end position, rather than showing each step they made.
What I have so far is:
while(bubble[1].getDegree() != 270)
{
long time = System.currentTimeMillis();
//the below if statement contains the function calls for
//the rotating bubble animations.
next();
draw();
// delay for each frame - time it took for one frame
time = (1000 / fps) - (System.currentTimeMillis() - time);
if (time > 0)
{
try
{
Thread.sleep(time);
}
catch(Exception e){}
}
}
public void draw()
{
for(int i = 1; i < bubble.length; i++)
{
iconLabel[i].setLocation(bubble[i].getX(), bubble[i].getY());
textLabel[i].setLocation((bubble[i].getX()+10),(bubble[i].getY()+10));
}
}
For clarity, the method "next()" merely changes the position of the bubble to the appropriate place, I know this to be functioning as I have had the animation work before but once I implemented the animation to JLabels it stopped working.
Any help would be appreciated.
The drawing is frozen because you block the event dispatch thread. Drawing is done in the same thread as the while loop, and since the loop prevents anything else happening while it's running, swing can get to drawing only after the loop is finished, so only the last position is drawn.
Use a swing Timer instead:
timer = new Timer(delay, new ActionListener() {
public void actionPerformed(ActionEvent e) {
// whatever you need for the animation
updatePositions();
repaint();
}
});
timer.start();
And then call timer.stop() when all the frames you need have been processed.

Sleeping a Thread in Canvas

In my game I want to draw the screen black after losing or winning a level and then draw a message in white on to the screen. After a few seconds delay I then want the screen to disappear when touched. Below is part of my draw() method. The problem is that screen freezes (or the thread sleeps) before the screen is drawn black and the text is drawn, even though the sleep command is after the text and canvas is drawn. Any ideas why this is happening?
if (state == WIN || state == LOSE){
canvas.drawColor(Color.BLACK);
message = "Touch Screen To Start";
canvas.drawText(message + "", mCanvasWidth / 2, mCanvasHeight / 2, white);
try {
GameThread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
I have a feeling that the canvas function doesn't actually display anything until it returns. Especially if you are running on Android >3.0 with hardware acceleration, or any configuration with double buffering, it won't actually update the screen until it finishes.
Instead when you draw the black screen, store the current time. Something like:
mStartTime = System.currentTimeMillis();
Then in the function watching for presses, check how many seconds have passed and see if enough time is happening, something like:
if( (System.currentTimeMillis() - mStartTime)/1000 > 5){
//Put code here to run after 5 seconds
}
This should draw your text and avoid blocking the Ui thread (a big no no in every respect).
It could be that the call to drawText is taking a few fractions of a second longer than you realize, and since you immediately call sleep, you are actually sleeping the thread before you draw.
Try putting a small loop, for( i < 10000 ) or something before the call to sleep and see if that helps.
Use CountDownTimer
http://developer.android.com/reference/android/os/CountDownTimer.html
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
// Here you do check every second = every 1000 milliseconds
}
public void onFinish() {
// Here you can restart game after 30 seconds which is 30K milliseconds.
mTextField.setText("done!");
}
}.start();

Categories

Resources