How to add time events in libgdx - java

I wanted to know how can I add time to my events in libgdx. I have a button and when you press it a sprite will appear. I want the sprite to appear for only a short period of time. How can I do this? I used Scene2D to make the sprites as an actor.
I will show you an example in pseudo code.
wait time = 5 second;
current time = get time;
if (current time > wait time) {
// do the following
}

There's two ways to do this. You can either use something similar to your your pseudo code or you can use a timer.
Manual calculation:
private Long lifeTime;
private Long delay = 2000L; //1000 milliseconds per second, so 2 seconds.
public void create () {
lifeTime = System.currentTimeMillis();
}
public void render () {
lifeTime += Gdx.graphics.getDeltaTime();
if (lifetime > delay) {
//Do something
}
}
Using a timer:
private float delay = 2; //In seconds this time
//At some point you set the timer
Timer.schedule(new Task(){
#Override
public void run() {
// Do something
}
}, delay);
Read more here: https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/utils/Timer.html

Related

How to change the delay of a Timer for every time it runs?

Right now I have a timer that has a delay of 5 seconds, however I need a different delay after it has run once.
I am going through some pictures and during the first round it should show them for 5 seconds. After that it should show them for 10 seonds. How is it possible to change the delay of a Timer during runtime?
What has to happen:
Start Timer
Run for 5 seconds
Change delay
Run for 10 seconds
Try to add some code!
You need to check if the timer has 5 seconds make it 10 and so on.
int delayTime = 5;
//run first delay
if (delayTime == 5){
delayTime = 10;
}
This is some code for the idea, don't know how it looks in your project.
There can be two approach for your use case:
First Approach:
Like say I want to show the picture for 1000 seconds. So I will execute for loop till 1000 seconds; or if you want to run it infinitely then you can change the condition in for loop. Below code will execute the for loop after every 5 seconds delay.
int delayTimeInMiliSec;
for(int delayTime = 5 ; delayTime<=1000; delayTime = delayTime+5){
delayTimeInMiliSec = delayTime * 1000;
// here Call your method that shows pictures
Thread.sleep(delayTimeInMiliSec);
}
Second Approach:
create a class extending TimerTask(available in java.util package). TimerTask is a abstract class.
Write your code in public void run() method that you want to execute periodically.
Code sample:
import java.util.TimerTask;
// Create a class extends with TimerTask
public class ScheduledTask extends TimerTask {
// Add your task here
#Override
public void run() {
//show pictures code
}
}
import java.util.Timer;
public class SchedulerMain {
public static void main(String args[]) throws InterruptedException {
Timer time = new Timer(); // Instantiate Timer Object
ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
time.schedule(st, 0, 5000); // Create Repetitively task for every 5 secs
}
}

Calculate FPS in Java Game [duplicate]

This question already has answers here:
Calculating frames per second in a game
(21 answers)
Closed 9 years ago.
Yesterday I wrote a Thread addressing how my game loop ran (in java) and how it works.
My game loop works completely, and I know why, but now I just wan't to know how to calculate FPS (Frames Per Second) and print it out every second.
I got a response yesterday about this, but he/she explained it in words and I couldn't understand it.
If anyone could help me (with a code example? :D) that would be great.
Here is my game loop:
while (running) {
start = System.nanoTime();
update();
draw();
drawToScreen();
elapsed = System.nanoTime() - start;
wait = targetTime - elapsed / 1000000;
if (wait < 0) {
wait = 5;
}
try {
Thread.sleep(wait);
} catch (Exception e) {
Game.logger.log("ERROR! Printing Stacktrace...");
e.printStackTrace();
}
}
ALSO:
In my JFrame when ever I call setName(string) it never works/updates on the Frame - Link me to a thread?
The easiest way to do this is to keep a variable whatTheLastTimeWas stored and doing this where you want to check your frame rate:
double fps = 1000000.0 / (lastTime - (lastTime = System.nanoTime())); //This way, lastTime is assigned and used at the same time.
Alternatively, you can make a FPS counter like so:
class FPSCounter extends Thread{
private long lastTime;
private double fps; //could be int or long for integer values
public void run(){
while (true){//lazy me, add a condition for an finishable thread
lastTime = System.nanoTime();
try{
Thread.sleep(1000); // longer than one frame
}
catch (InterruptedException e){
}
fps = 1000000000.0 / (System.nanoTime() - lastTime); //one second(nano) divided by amount of time it takes for one frame to finish
lastTime = System.nanoTime();
}
}
public double fps(){
return fps;
}
}
Then in your game, have an instance of FPSCounter and call nameOfInstance.interrupt(); when one frame is finished.
You can combine a simple counter and Timer.scheduleAtFixedRate for this.
Disclaimer: I don't know if this is the best method; it's just easy.
int totalFrameCount = 0;
TimerTask updateFPS = new TimerTask() {
public void run() {
// display current totalFrameCount - previous,
// OR
// display current totalFrameCount, then set
totalFrameCount = 0;
}
}
Timer t = new Timer();
t.scheduleAtFixedRate(updateFPS, 1000, 1000);
while (running) {
// your code
totalFrameCount++;
}

Slow down the call to a specific function

I have a game loop here, that calls the tick method. Inside the tick method, other tick methods are called. How would I slow down the call to input.tick() without slowing down the whole program? Putting a Thread.sleep(); anywhere in the tick methods slows down the whole program and that is not what I want.
public void run() {
long lastTime = System.nanoTime();
long timer = System.currentTimeMillis();
final double ns = 1000000000.0 / 60.0;
double delta = 0;
int frames = 0;
int ticks = 0;
while(running){
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1){
tick();
ticks++;
delta--;
}
render();
frames++;
if(System.currentTimeMillis() - timer > 1000){
timer += 1000;
System.out.println(ticks + " tps, " + frames + " fps");
ticks = 0;
frames = 0;
}
}
stop();
}
public void tick(){
input.tick(); // How do I slow down the call to this?
if(gameState){
player.tick();
player.move();
collision();
treeline.move();
obstacleHole.move();
obstacleWolf.move();
coin.move();
coin.tick();
}
}
It seems you are doing a GUI application and the code you are showing runs on the Event Dispatch Thread. The sleeps make the EDT freeze and be unable to update the GUI. What you must do instead is use the javax.swing.Timer class to postpone the execution of the code.
If you want to tick at regular intervals, then just reschedule the same task again in the handler submitted to Timer.
Use a Thread to call tick() in a deferred way, something like this:
private static final Timer TIMER = new Timer();
// ...
public void tick(){
TIMER.schedule(new TimerTask(){
void run() {
input.tick(); // Your tick method
}
}, 1000 /* delay in milliseconds */)
// ... rest of your method
}
If the input.tick() method collects the input of the player (e.g. key presses) it does no seem appropriate to delay it.
Perhaps you might be interested in implementing a Keyboard Input Polling mechanism. (see here for an example).
This is a usual technique in games so you do not respond to the input of the player in the usual way you would with other GUI applications. Instead you collect all the user input e.g. in a queue and then you poll that queue to read input at your own speed (e.g. 30 times per second).
I hope it helps

I want to add timer in my applet

I made CountDown.java file and try to add in my Word-trouble.java file (which is main applet) as CountDown ct = new CountDown();
but it is not showing timer in main applet.
Here is coding:
package pack.urdu;
import java.awt.*; //windows toolkit
import java.applet.*; //applet support
public class CountDown extends Applet implements Runnable{
int counter; Thread cd;
public void start() { // create thread
counter = 60; cd = new Thread(this); cd.start();
}
public void stop() { cd = null;}
public void run() { // executed by Thread
while (counter>0 && cd!=null) {
try{Thread.sleep(1000);} catch (InterruptedException e){}
--counter; repaint(); //update screen
}
}
public void paint(Graphics g) {
g.drawString(String.valueOf(counter),25,75);
}
}
You are making a mistake that I see a lot of programmers make: you are mixing up the calculation of elapsed time, with the calculation of the refresh time. If the duration of sleep takes long than a second because of thread contention, your timer will drift.
Instead of tracking a counter that increments every second, just record the start time:
long startTime = System.currentTimeMillis();
Then later, your paint method becomes:
public void paint(Graphics g) {
int elapsedSeconds = (int)(System.currentTimeMillis()-startTime)/1000
g.drawString(String.valueOf(elapsedSeconds),25,75);
}
This method can be called as often, and as many times as you like, and it will always display the correct elapsed seconds. There is no need to increment anything at any specified time.
The only other thing you have to do is to arrange that the screen gets refreshed. (I like to say that you only have to refresh the screen when the user looks at it :-) but since we don't know that we need to refresh more often). The mechanism for this may depend upon the graphic library. One lazy idea is to refresh ten times a second and the screen will be right most of the time.
If you do want to have a thread that sends repaint events, you should have those events sent just at the time that timer clicks over to a new value, and thereby send only one per second. This is done with:
while (stillRunning) {
long elapsedTime = System.currentTimeMillis() - startTime;
long timeTillNextDisplayChange = 1000 - (elapsedTime % 1000);
Thread.sleep(timeTillNextDisplayChange);
repaint();
}
Note that you do not sleep 1000ms! If your system is performing well, this will be very close to 1000ms, but slightly less than that to account for (1) the thread startup delay, possibly caused by thread contention, and (2) the processing time for this loop (which is quite small). In any case, calculating the sleep in this way will prevent timer drift, and assure that your display updates just as the seconds value changes.
See an extended discussion of Common Misunderstandings of Timers on my website.

In Java, how do I execute code every X seconds?

I'm making a really simple snake game, and I have an object called Apple which I want to move to a random position every X seconds. So my question is, what is the easiest way to execute this code every X seconds?
apple.x = rg.nextInt(470);
apple.y = rg.nextInt(470);
Thanks.
Edit:
Well do have a timer already like this:
Timer t = new Timer(10,this);
t.start();
What it does is draw my graphic elements when the game is started, it runs this code:
#Override
public void actionPerformed(ActionEvent arg0) {
Graphics g = this.getGraphics();
Graphics e = this.getGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
e.fillRect(0, 0, this.getWidth(), this.getHeight());
ep.drawApple(e);
se.drawMe(g);
I would use an executor
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Runnable toRun = new Runnable() {
public void run() {
System.out.println("your code...");
}
};
ScheduledFuture<?> handle = scheduler.scheduleAtFixedRate(toRun, 1, 1, TimeUnit.SECONDS);
Use a timer:
Timer timer = new Timer();
int begin = 1000; //timer starts after 1 second.
int timeinterval = 10 * 1000; //timer executes every 10 seconds.
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//This code is executed at every interval defined by timeinterval (eg 10 seconds)
//And starts after x milliseconds defined by begin.
}
},begin, timeinterval);
Documentation: Oracle documentation Timer
Simplest thing is to use sleep.
apple.x = rg.nextInt(470);
apple.y = rg.nextInt(470);
Thread.sleep(1000);
Run the above code in loop.
This will give you an approximate(may not be exact) one second delay.
You should have some sort of game loop which is responsible for processing the game. You can trigger code to be executed within this loop every x milliseconds like so:
while(gameLoopRunning) {
if((System.currentTimeMillis() - lastExecution) >= 1000) {
// Code to move apple goes here.
lastExecution = System.currentTimeMillis();
}
}
In this example, the condition in the if statement would evaluate to true every 1000 milliseconds.

Categories

Resources