How to make blinking animation in LibGDX - java

I'm trying to create a sequence of actions to simulate eye blinking of my character but I have no idea how to properly do this. I need it to stand still for like 5 secs, then blink once and wait for 5 seconds again and loop forever. Hope someone could shed some light here.
This is what I've got so far which doesn't work to what I have expected (After 3f, it will keep blinking, how do I detect blinking animation end and reset back to stand?):
this.addAction( Actions.sequence(
Actions.run( new Runnable() {
#Override
public void run() {
stand();
}
}),
Actions.delay(.3f),
Actions.run( new Runnable() {
#Override
public void run() {
blink();
}
})));

Libgdx has a class RepeatAction, which is what you are looking for.
Basicly you need to call:
this.addAction(Actions.forever(Actions.sequence(
Actions.run(new Runnable {
#Override
public void run() {
stand();
}
}),
Actions.delay(0.3f),
Actions.run(new Runnable {
#Override
public void run() {
blink();
}
});
)));
But instead of using new Runnable you may use one of the methods provided by Libgdx Actions.
So for example, the stand(), isn't it only "do nothing"? This can be achieved with an Actions.delay(5f), which waits for 5 seconds.
And the blink() isn't it only switching from "visible" to "invisible"?
This could be don with Actions.alpha(0, 0.2f), which changes the characters transparency from its current to 0 in 0.2 seconds. Then you could add another delay to let the character "wait" in the invisible state and make it visible again with Actions.alpha(1, 0.2f).
Hope it helps.

Related

How can I pause/continue scheduled task?

I'm new to JAVA and trying to learn some concurrency concepts.
I have a simple GUI class that pops-up a window with 1 button which I want to use for pause/continue.
Also, I have a class that extends TimerTask, it looks like below and start with the GUI:
public class process extends TimerTask {
public void run() {
while(true) { /*some repetitive macro commands.. */ }
}
}
Real question is, how can I pause the task onClick of the button and also continue onClick of the button if already paused?
I have taken a step to use a boolean to flag the button as it changes from pause to continue on each click.
But then I had to type a lot of while(button); for busy waiting inside the while()...
Do you think I can make like Thread.sleep() or something but from outside the task thread?
OLD ANSWER
Basically, there is no support for pause and resume on TimerTask, you can only cancel, check here
perhaps you might want to read about threading as that's the alternative I know of that has an interrupt and start features and then you can keep track of the progress of what you're doing to resume where it stopped.
So, I will suggest you go through this link, because you need to understand threading not just copy a code to use, there is a sample code there that will definitely solve your problem also.
Note that running an endless while loop will basically cause your program not to respond, unless the system crashes. At a certain point, the data becomes an overload and the program will overflow. This means it will fail.
.
NEW ANSWER
So, response to the new question, I was able to run a tiny little program to demonstrate how you can achieve something that looks like multithreading when working with SWING.
To rephrase your question: You want to run an indefinite task like let say we're playing a song, and then onclick of a button to pause the song, on click again should continue the song?, if so, I think below tiny program might work for you.
public class Test{
static JLabel label;
static int i = 0;
static JButton action;
static boolean x = false; //setting our x to false initialy
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
label = new JLabel("0 Sec"); //initialized with a text
label.setBounds(130,200,100, 40);//x axis, y axis, width, height
action=new JButton("Play");//initialized with a text
action.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(action);//adding button in JFrame
f.add(label);
action.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
if(x){
x = false; //Update x here
action.setText("Play");
action.revalidate();
}else{
x = true; //Update x here also
action.setText("Pause");
action.revalidate();
if(x){ //Using x here to determind whether we should start our child thread or not.
(new Thread(new Child())).start();
}
}
}
});
f.setSize(500, 700);//500 width and 700 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
class Child implements Runnable{
#Override
public void run() {
while (x) {
//You can put your long task here.
i++;
label.setText(i+" Secs");
label.revalidate();
try {
sleep(1000); //Sleeping time for our baby thread ..lol
} catch (InterruptedException ex) {
Logger.getLogger("No Foo");
}
}
}
}

Delaying a java programme involving a GUI without Thread.sleep()

I'm currently programming a mini game in java swing. I've got the GUI set up, and the game involves a sequence of numbers flashing up on screen and then disappearing - the user must then input the numbers again in the sequence they appeared.
When the numbers are initially displayed, I want them to display for 1-2 seconds, and then disappear, and have another number for 1-2 seconds etc.
However, I'm having issues with delaying the program whilst the number displays. I can't use Thread.sleep as it pauses the whole program with the hiding of previous numbers etc. It just doesn't work. I've tried every other suggestion I've come across, none of which have worked yet.
Anyone got anymore tips?
int delay = 5000; // delay in milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) { //...Perform a task... } };
Timer timer = new Timer(delay, taskPerformer);
timer.setRepeats(false);
timer.start(); // timer starts - after delay time your task gets executed
Source
You can use Thread.sleep()
The problem you having is probably because you are trying to update the UI from Swing's event dispatching thread. This is a thread that is reserved for Swing components and you should do exactly nothing in it except quick updates to the UI.
public void prog() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
label.setText("1");
}
}
try {
Thread.sleep(5000);
} catch(Exception e) { }
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
label.setText("2");
}
}
}
public static void main(String[] args) {
label = new JLabel("0");
prog();
}
JLabel label
The UI should remain responsive because of it's component interactions should be implemented in ActionListener's. But if you want to perform other work while waiting, or if the feature is contained in an ActionListener's actionPerfomed() method, you can kick off a new thread to sleep 5 seconds then update the UI. You could also perform some calculations that take 5 seconds to compute instead of sleeping without blocking the UI. The code would be:
(new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(5000);
} catch (Exception e) { }
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
label.setText("2");
}
}
}
}).start();

Andengine TimerHandler and detecting collisions

I'm developing a game where LittleMan can move from block to block, and certain blocks are moving. I'm trying to detect when he moves to a new moving block, if that block is beneath him or if it has moved. I'm using Andengine's TimerHandler to check every 0.1 seconds but it is not working. Here's the code:
private void OnMovingBlock(final int CurrentPosRow, final int CurrentPosColumn) {
this.getEngine().registerUpdateHandler(new TimerHandler(0.1f, true, new ITimerCallback() {
#Override
public void onTimePassed(final TimerHandler pTimerHandler) {
if (LittleManPos[0] == CurrentPosRow && LittleManPos[1] == CurrentPosColumn) {
if (!LittleMan.collidesWith(MapRectangles[CurrentPosRow][CurrentPosColumn])) {
RestartScene();
}
}
}
}));
}
It seems he can move to the block and sit there with it moving in and out beneath him but it doesn't call RestartScene() UNTIL I move him again. Any idea where I am going wrong? Or is there another way to do this?
Why don't create a Timer?
TimerTask task = new TimerTask(){
#Override
public void run(){
// your code goes here
}
};
Timer timer = new Timer();
timer.sechedule(task, 0, 100); // 100 --> 0.1 second
To cancel the Timer, call timer.cancel();.

Updating TextView In One Function

I want to do something very simple. I have a progress-bar and a textView that I want to dynamically update on a button click, but more than once during the function call.
I want it to change to 'A' then wait a second, then switch to 'B' ... for example.
I understand that my function blocks the UI/main thread, which is what if I setText() ten times, I only see the tenth text appear when the function completes.
So I've tried handlers/runnables in the UI thread, invalidating (and postInvalidating) to encourage refreshing and runOnUiThread() and they all just update when they've finished running leaving me only with the final state.
public void requestPoint(View v) {
textProgress.setText("Requesting A Point");
waiting(200);
progressBar.setProgress(5);
textProgress.setText("Request Received!");
waiting(500);
....
}
I think I've turned nearly all the similar question links purple and wasted way too much time on this simple thing (although I did learn a lot about threading on Android) but I feel I must be missing something crucial, this doesn't seem like that hard of task.
Any help would be greatly appreciated.
Assuming you really do just want to waste time with your waiting method. This is assuming a 200ms delay followed by a 500ms delay like in your example.
public void requestPoint(View v) {
textProgress.setText("Requesting A Point");
handler.postDelayed(new Runnable(){
public void run(){
progressBar.setProgress(5);
textProgress.setText("Request Received!");
}
}, 200);
handler.postDelayed(new Runnable(){
public void run(){
....
}
}, 700);
....
}

Java Timer not working

I have an Image named worldImageToUse and I have a Timer that is supposed to toggle worldImageToUse between two images every 1 second. But it does not seem to work. Help Please?
public void startWorldImageFlash() {
worldImageFlashTimer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
if(worldImageToUse == worldImage) setWorldImageBW();
if(worldImageToUse == worldImageBW) setWorldImageColor();
}
};
worldImageFlashTimer.scheduleAtFixedRate(task, 0, 1000);
}
public void stopWorldImageFlash() {
worldImageFlashTimer.cancel();
setWorldImageColor();
}
Checked twice, change the second if with "else if", that will solve the problem. Also, you should consider debugging in such cases :)
It looks like your code says if color set to black and white. Then says if black and white set to color. Wouldn't you end up with the same image every time. Your second if needs to be an else if.
Did you repaint() the component afer setting the image?

Categories

Resources