Whats the best way to put a number in a variable on a button click?

edited October 2016 in Questions about Code

We have made a small game with a variable to get the amount of enemies in the game, like: int enemies = 1;

Now we would like to make a menu where the user can select the amount of enemies by clicking on a button, like:

if(mouseX >= space && mouseX <= buttonWidth()+space && mouseY >= yPosButton() && mouseY <= yPosButton()+buttonHeight()){
     //button one
     enemies = 1;
}

if(mouseX >= (space*2)+buttonWidth() && mouseX <= (buttonWidth()*2)+(space*2) && mouseY >= yPosButton() && mouseY <= yPosButton()+buttonHeight()){
     //button two
     enemies = 2;
}

 …

But we think this is not really the best approach, we have looked at a switch/case menu but its only good for switching screens, not for filling in a variable. Whats the best way of making this work?

Tagged:

Answers

  • It is better if you post your code or a small sample code showing your approach. In your example above, you don't show how you defined your buttons nor how many buttons you are using. On another topic, switch case is a programming structure and not confined to switching screens. It is possible to clarify this is you post your relevant code.

    Kf

  • edited October 2016 Answer ✓

    Options:

    • Create your game menu using a GUI library, like ControlP5 or G4P, which you can install through the Processing contributions manager. It has special objects for buttons, text fields, etc. etc. The library is big, complex, and hard to set up, but powerful and robust.

    • Use the keyboard! While your menu is open (or maybe all the time), map two buttons against changing the enemy number up and down, e.g. "+/-"

    Example sketch:

    /**
     * Simple keyboard variable
     * 2016-10-24
     * https:// forum.processing.org/two/discussion/18685/whats-the-best-way-to-put-a-number-in-a-variable-on-a-button-click
     **/
    int enemies;
    int minEnemies;
    int maxEnemies;
    boolean menuOpen = true;
    
    void setup(){
      enemies = 1;
      minEnemies = 1;
      maxEnemies = 9;
    }
    void draw(){
      background(0);
      text("ENEMIES: - " + enemies + " +",5,12);
    }
    void keyPressed(){
      if(menuOpen){
        if((key=='+')||key=='='){ enemies++; }
        if(key=='-'){ enemies--; }
        enemies = constrain(enemies, minEnemies, maxEnemies);
        println("ENEMIES:", enemies);
      }
    }
    

    SimpleKeyboardVariable_console

    • Create +/- buttons in your menu, and combine your button-box-detection code above with a change-the-variable approach in the previous example.
  • Amazingly clever thinking @jeremydouglass this definitely helps! Also thanks to the other people responding to the question :)

Sign In or Register to comment.