-2

In LibGDX's update method, is it possible to make an action happen only once when told to, without doing this? :

private boolean shouldBeFired = false;
    @Override
    public void update(float dt) {
        if(shouldBeFired)
            fire();
            shouldBeFired = false;
}
vladutelu
  • 157
  • 1
  • 7
  • `without a boolean` ? , it's better to say `without any flag` – Abhishek Aryan Jun 03 '17 at 16:40
  • 1
    Changed the title – vladutelu Jun 03 '17 at 16:41
  • 1
    with flag it should be like this `if(shouldBeFired) { fire(); shouldBeFired = false; }` – Abhishek Aryan Jun 03 '17 at 16:44
  • https://stackoverflow.com/questions/17701197/how-to-run-code-inside-a-loop-only-once-without-external-flag – hsirkar Jun 03 '17 at 16:44
  • @PaperTowel thanks for the link, but I am not very familiar with structs. Could you provide some info on them as well? I couldn't find anything on the internet – vladutelu Jun 03 '17 at 17:58
  • Also, keep in mind that this is Java, not C++. I have read the thread you linked me more thoroughly and I have noticed things that are not possible in Java, such as declaring a static boolean in a for loop – vladutelu Jun 03 '17 at 18:19
  • Yes, post tasks to the Timer class. It's explained in the documentation. Although it's a bit different than what you asked for because it will fire even if you aren't calling update(). – Tenfour04 Jun 03 '17 at 20:47
  • you could implement an event queuing system, put it on the stack, and it would disappear when executed. Maybe libgdx does this already. I've used something similar in a different framework. – ether_joe Jun 04 '17 at 04:41
  • Is there a reason you can't use a boolean as an external flag? Your code (aside from what Abhishek Aryan mentioned) seems fine to me. – hsirkar Jun 04 '17 at 04:48
  • @PaperTowel I am making an android app and I am trying to make everything as efficient as possible. If I used a boolean for everything that needed to be run once in the update method, I would have a lot of flags and I don't know if it's optimal – vladutelu Jun 04 '17 at 06:55
  • It seems that is the best you can do with java. I usually use an integer instead of a boolean (`int a = 0; ... if (a < 1) { fire(); a++;}`) but that's just personal preference. – hsirkar Jun 05 '17 at 02:20

1 Answers1

0

If number of flags is the problem you can use int or even more optimal you can use enum for your requirement.

enum MyFlag{
    NONE,FIRST,SECOND,THIRD,FOURTH
}

MyFlag myFlag=MyFlag.NONE;

@Override
public void update(float dt) {
    if(myFlag==MyFlag.FIRST) {
        fire();
        myFlag=MyFlag.values()[myFlag.ordinal()+1]; // incremental change

        //or manually change

        myFlag=MyFlag.NONE;
    }
}

Number of constant flag under one roof is good option for optimal development.

Abhishek Aryan
  • 19,936
  • 8
  • 46
  • 65