help on project with multiple sketches

Hello guys,

I need help again, I will try to explain ...

I'm adapting some sketches (obtained in OpenProcessing, where I am adjusting to a project at the company where I work ...), two of them are in these links:

http://www.openprocessing.org/sketch/31621 http://www.openprocessing.org/sketch/175059

In this case, when I run individualistically, has a paint effect that seems to be "swiping" ... OK, this is how we like to run it.

My problem occurs when I add in the project along with other scketchs, so that work in sequence (options, it would be more appropriate to say ...)

When I run within the project, has a different effect, is "cut through" the design, changing the way ...

My question then is, has anyone ever seen this effect (just changing a command to switch the route?)

I decided not to put the code, at least for now, to be a bit long (with the multiple sketches), just put the prints, to have an idea of ​​what's going on, if need be, later put here.

Thank you for your attention now.

Thank you,

José Aparecido Tela01 Tela02 Tela3 Tela4 Tela05

Answers

  • here I demonstrate how to join different sketches.

    You need one setup() and draw()

    these can call

    • setup0(), draw0() (the former old sketch 1)

    • setup1(), draw1() (the former old sketch 2)

    • etc.

    did you mean that?

    here comes a version with images.

    the images must be in the sketch folder.

    they must be called 0.jpg, 1.jpg, 2.jpg (exactly like that)

    ;-)

    // states -------------------------------
    // consts: possible values 
    final int normal = 0;
    final int program0 = 1;
    final int program1 = 2;
    final int program2 = 3;
    int state = normal; // var: current value
    
    // buttons --------------------------
    Button[] buttons;
    
    // Misc for programs ------------------------------ 
    PVector helpPoint =new PVector();  // for Line etc., Point #1
    PVector helpPoint2=new PVector();  // Point #2
    PVector helpPointAdd;     // vector for moving Point #1
    PVector helpPoint2Add;    // vector for moving Point #2
    
    //-------------------------------------------------
    // the core functions 
    
    void setup() {
      size(400, 700);
    
      // these are local vars (their scope is only setup()
      int countButton = 3;
      int sizeButton = 45;
      PImage[] images = new PImage[3];
    
      // declare the array of the buttons
      buttons = new Button[countButton];
    
      // read images for the buttons --------------------------
      for (int i = 0; i < countButton; i++) {
        images[i] = loadImage(trim(str(i)) + ".jpg");
        images[i].resize(sizeButton, sizeButton);
      } // for 
    
      // creating the buttons ---------------------------
      for (int i = 0; i < countButton; i++) {
        buttons[i] = new Button(66, i*55+33, 
        sizeButton, 
        color(255, 0, 0), color(0, 255, 0), color(0, 0, 255), 
        i, 
        images[i]);
      } // for 
      //
    } // func 
    
    void draw() {
      background(0, 0, 0);
      // eval state 
      if (state==normal) {
        text("Please select one sketch to show", 17, 17);
        // short version of a for-loop
        for (Button but : buttons) {
          but.update();
          but.display();
        }
      } else if (state==program0) {
        draw0();
      } else if (state==program1) {
        draw1();
      } else if (state==program2) {
        draw2();
      } else {
        // error 
        println ("Unknown state (error #965)");
      }
    } // func 
    
    //-------------------------------------------------
    // Inputs 
    
    void mousePressed() {
      // eval state 
      if (state==program0 || state==program1 || state==program2) {
        // in the sub-sketches: go back to normal 
        state = normal;
      } else if (state==normal) {
        // in the main sketch: eval buttons 
        for (Button but : buttons) {
          but.press();
          if (but.pressed) {
            evalButton(but); 
            break; // Other buttons won't be pressed, just stop
          } // if
        } // for
      } // else if
      else {
        // error 
        println ("Unknown state (error #1065)");
      }
    } // func 
    
    void evalButton(Button but) {
      println(but.index);
      if (but.index==0) { 
        setup0(); 
        state=program0;
      } else if (but.index==1) { 
        setup1(); 
        state=program1;
      } else if (but.index==2) { 
        setup2(); 
        state=program2;
      } else {
        println ("Unknown button index (error #1165)");
      }
    } // func 
    
    void mouseReleased() {
      for (Button but : buttons) {
        but.release();
      }
    } // func 
    
    void keyPressed() {
      state=normal; // return to normal state 
      key=0; // kill escape
    } // func 
    
    // --------------------------------------------
    // the sub-sketches we want to start 
    
    void setup0() {
      initPointsForLine();
    } // func 
    
    void draw0() {
      stroke(0, 255, 0);
      line (helpPoint.x, helpPoint.y, 
      helpPoint2.x, helpPoint2.y );
      checkHelpPointsForLine();
    } // func 
    
    // ---
    
    void setup1() {
      initPointsForLine();
    } // func 
    
    void draw1() {
      stroke(0, 255, 0);
      ellipse (helpPoint.x, helpPoint.y, 10, 10);
      ellipse (helpPoint2.x, helpPoint2.y, 10, 10 );
      checkHelpPointsForLine();
    } // func 
    
    // ---
    
    void setup2() {
      initPointsForLine();
    } // func 
    
    void draw2() {
      stroke(0, 255, 0);
      rect (helpPoint.x, helpPoint.y, 
      helpPoint2.x-helpPoint.x, helpPoint2.y-helpPoint.y );
      checkHelpPointsForLine();
    } // func 
    
    // ----------------------------------------------
    // help funcs for the sub-sketches
    
    void initPointsForLine() {
      // invisible help lines on the left side leading to green line 
      helpPoint = new PVector(random(width), random(height));
      helpPoint2 = new PVector(random(width), random(height));
      helpPointAdd = new PVector(random(-2, 2), random(-2, 2));
      helpPoint2Add = new PVector(random(-2, 2), random(-2, 2));
    } // func 
    
    void checkHelpPointsForLine() {
      // lines on the left side leading to green line on page 1
      helpPoint.add(helpPointAdd);
      helpPoint2.add(helpPoint2Add);
    
      // check helpPoint ----------------------------
      helpPointAdd.x = keepInBoundary(helpPoint.x, 12, width-13, helpPointAdd.x);
      helpPointAdd.y = keepInBoundary(helpPoint.y, 13, height -13, helpPointAdd.y);
      // check helpPoint2 ----------------------------
      helpPoint2Add.x = keepInBoundary(helpPoint2.x, 12, width-13, helpPoint2Add.x);  
      helpPoint2Add.y = keepInBoundary(helpPoint2.y, 13, height -13, helpPoint2Add.y);
    } // func 
    
    float keepInBoundary(float testPoint, float lowerBoundary, float upperBoundary, float valueToAdd) {
      // Situation: testPoint is a ball position and valueToAdd gets added to it, so testPoint flies. 
      // Now testPoint must stay within lowerBoundary and upperBoundary (e.g. screen). 
      // ValueToAdd gets changed accordingly and is returned as return value.
      if (testPoint<lowerBoundary) {
        valueToAdd=abs(valueToAdd);
      }
      if (testPoint>upperBoundary) {
        valueToAdd=-1*abs(valueToAdd);
      } 
      return valueToAdd;
    } // func 
    
    
    // ------------------------------------------
    // classes 
    
    class Button {
    
      int x, y; // The x- and y-coordinates
      int size; // Dimension (width and height)
      color baseGray; // Default gray value
      color overGray; // Value when mouse is over the button
      color pressGray; // Value when mouse is over and pressed
      boolean over = false; // True when the mouse is over
      boolean pressed = false; // True when the mouse is over and pressed
      int index; // index 
      PImage img; // image 
    
      // the constructor (the underscore _ says I'm temp)
      Button(int xp_, int yp_, 
      int s_, 
      color b_, 
      color o_, 
      color p_, 
      int index_, 
      PImage img_ ) {
        x = xp_;
        y = yp_;
        size = s_;
        baseGray = b_;
        overGray = o_;
        pressGray = p_;
        index=index_;
        img=img_;
      } // the constructor 
    
      // Updates the over field every frame
      void update() {
        if ((mouseX >= x) && (mouseX <= x + size) &&
          (mouseY >= y) && (mouseY <= y + size)) {
          over = true;
        } else {
          over = false;
        }
      }
    
      boolean press() {
        if (over == true) {
          pressed = true;
          return true;
        } else {
          pressed = false;
          return false;
        }
      }
    
      void release() {
        // Set to false when the mouse is released
        pressed = false;
      }
    
      void display() {
        //    if (pressed == true) {
        //      fill(pressGray);
        //    } else if (over == true) {
        //      fill(overGray);
        //    } else {
        //      fill(baseGray);
        //    }
        // rect 
        //  stroke(255);
        //  rect(x, y, size, size);
        // image 
        image(img, x, y);  
        // text to the right
        fill(0, 255, 0);
        text(index, x+size+17, y+size/2);
      }
    }
    // ==============================================
    
  • Hi Chrisir,

    I managed to control options as you said last time, I'm able to develop the project based on this principle, program1, program2, etc., works very well ...

    The problem I'm having is that has an "unexpected effect" when run within the project with various sketches, because when I run individually have another result, as shown in the pictures.

    The problem is that as I have several sketches, it would be a little tricky to know when can be being changed some setting that causes this change effect, so I asked if anyone knows how to provoke this purpose effect, so I can see where you are going to change to occur it.

    I will leave here of the code code, to have an idea what I'm trying to explain ... as I said before, excuse the failure to communicate in English ... rsss ...

    ... Print how the programs are divided, and the menu running, with various options (works great). Menu01

    Part of the project code (will not compile, because it contains everything you need here ...)

    void draw() {
      if (limpaTela) background(r, g, b); //Limpa tela com a cor carregada
    
      //Compara opções para executar programa conforme definido ao selecionar o Botão 
      if (opcaoMenu == start) { //Menu Inicial
        if (menuAtivo == 1) {
          for (Button but : buttonsMenu1) {
            but.update();
            but.display();
            //txaInfo01.setVisible(but.over);
            //println("Over: " + but.over);
          }
        } else if (menuAtivo == 2 ) {
          for (Button but2 : buttonsMenu2) {
            but2.update();
            but2.display();
          }
        }
    
        textFont(fontA, 40);
        fill(#1273C1);
        text("Selecione uma Opção para Começar...", 10, 30);
      } else if (opcaoMenu == animacao0) { //Animação específicas, compartilhadas com as demais
        draw0();
      } else if (opcaoMenu == animacao1) { //Animação Bolhas/Balões
        draw1();
      } else if (opcaoMenu == animacao2) { //Animação "Estoura balão" /Paint 
        draw2();
      } else if (opcaoMenu == animacao3) { //Animação desenho com linhas ( Formas )
        draw3();
      } else if (opcaoMenu == animacao4) { //Animação "Espalha tinta"
        draw4();
      } else if (opcaoMenu == animacao5) { //Animação voo pássaro
        draw5();
      } else if (opcaoMenu == animacao6) { //Animação Desenho livre ( Formas )
        draw6();
      } else if (opcaoMenu == animacao7) { //Animação Formas ( 01 )
        draw7();
      } else if (opcaoMenu == animacao8) { //Animação Formas ( 02 )
        draw8();
      } else if (opcaoMenu == animacao9) { //Animação video o Sapo não lava o pé
        draw9();
      } else if (opcaoMenu == animacao10) { //"Mini" Piano
        //draw10();
      } else if (opcaoMenu == animacao11) { //"Mini" Sintetizador
        draw11();
      } else if (opcaoMenu == animacao12) { //"Jogo" Bolas se chocando
        draw12();
      } else { 
        if (desenhaEsqueleto){
          textFont(fontA, 20);
          fill(#1273C1);
          text("Status Kinect : " + statusKinect, 10, 20);
        } else {
          println ("Opção não Encontrada! (erro #001)");
        }
      }
    
      if (usaEntradaAudio) atualizaSinalAudio();   //Interação com entrada de Áudio 
      if (usaEntradaSerial) atualizaSinalSerial(); //Interação com entrada Serial ( USB )
    
      if (usaKinect) {
        atualizaKinect(); //Atualiza Coordenadas com o Kinect
        if (desenhaCursorM) rob.mouseMove(pX, pY);
      } else if (usaLeapMotion){
        atualizaLeapMotion(); //Atualiza coordenadas com Leap Motion
        if (desenhaCursorM) rob.mouseMove(pX, pY);
      } else{
        //Atualiza posições das coordenadas com o Mouse, caso não estiver usando o Kinect ou Leap Motion
        pX = mouseX;
        pY = mouseY;  
      }
    
      if (mostraInfoDisp) {
        textFont(fontA, 20);
        fill(#1273C1);
        //noStroke();
    
        if (opcaoMenu == start) { 
          text("A - Habilita/Desabilita Entrada Áudio.", 10, 60);
          text("U - Habilita/Desabilita Entrada USB.", 10, 80);
          text("K - Habilita/Desabilita Kinect.", 10, 100);
          text("L - Habilita/Desabilita Leap Motion.",10,120);
          text("Obs.: Habilitado o Leap Motion, pode alternar o movimento da MÃO para o dedo INDICADOR, através das teclas 1 ou 2.",10,140);
        } else if (opcaoMenu == animacao1) { //Desenhando Bolhas  
          text("Seta PARA BAIXO, ou pressionando o botão 'Recarregar', alterna o tipo de animação.", 10, 60);
          text("Obs.: Quando chegar no último tipo de animação diferente, retorna a animação inicial.", 10, 80);
        } else if (opcaoMenu == animacao2) { //"Jogo" Balões
          text("Ao posicionar a mouse sobre o balão, 'estoura'.", 10, 60);
          text("Na tela de 'Final de Jogo', pressione espaço para recomeçar.", 10, 80); 
        } else if (opcaoMenu == animacao3 || opcaoMenu == animacao4 ) { //Desenha Formas/Tinta
          text("Seta PARA BAIXO, ou pressionando o botão 'Recarregar', alterna o tipo de animação.", 10, 60);
          text("Obs.: Quando chegar no último tipo de animação diferente, retorna a animação inicial.", 10, 80);
          text("Tecla espaço, limpa a tela.", 10, 100);
       } else if (opcaoMenu == animacao5) { //Voo do Pássaro
          text("Seta PARA BAIXO ou PARA CIMA, muda posição da Ellipse ( bola ).", 10, 60);
          text("Tecla + ( mais ) adiciona 'pequenos pássaros'.", 10, 80);
          text("Obs.: Cada vez que a ellipse passar na posição da cabeça do passáro, cria pequenos 'pássaros'.", 10, 100);
          text("Conforme são adiocionados pequenos 'pássaros', eles se agrupam em bandos.", 20, 120);
        } else if (opcaoMenu == animacao6 ) { //Desenho Livre
          text("Pressione a Seta PARA CIMA, para desenhar com o movimento do Mouse.", 10, 60);
          text("Tecla espaço, limpa a tela.", 10, 80);
        } else if (opcaoMenu == animacao7 || opcaoMenu == animacao8) { //Desenha Formas
          text("Pressione o mouse para Parar ou Continuar a animação.", 10, 60);
        } else if (opcaoMenu == animacao9) { //História o Sapo não lava o Pé
          text("Colocar melhor descrição, de como funciona para montar a história...", 10, 60);
        } else if (opcaoMenu == animacao11 ) { //Mini Piano
          text("Movimente o Mouse sobre as 'Teclas' para reproduzir o som.", 10, 60);
          text("Ao Clicar sobre a figura no topo, muda o tipo de som ( alterna em 2 tipos ).", 10, 80);
        } else if (opcaoMenu == animacao12 ) { //"Jogo" bolas se chocando
          text("Pressionando o mouse UMA VEZ, para animação.", 10, 60);
          text("Pressionando o mouse NOVAMENTE, CONTINUA a animação.", 10, 80);
          text("Pressionando o mouse NOVAMENTE E ARRASTANDO, cria objetos na animação.", 10, 100);
        } 
    
        if (opcaoMenu != start) 
          text("Pressionando a tecla ESC, retorna ao Menu Inicial.", 10, 40);
      }
    
      if (visualizaTexto) {
        textFont(fontA, 20);
        fill(#1273C1);
        text( "Kinect Habilitado: " + usaKinect + " - Dispositivo ativo: " + infoDispositivo + " - Valor Capturado: " + valorSinal, 10, height-10 );
      }
    
      //Atualiza informações sobre configurações
      //lblInfoDisp.setText(infoDispositivo);
    }
    
    void mouseMoved() {
      if (opcaoMenu == animacao1) { //Desenha Bolhas
        mouseMoved1();
      } else if (opcaoMenu == animacao2) { //Jogo Balões
        mouseMoved2();
      }else if (opcaoMenu == animacao3) { //Desenha Formas
        mouseMoved3();
      } else if (opcaoMenu == animacao4) { //"Espalha Tinta" /Paint
        mouseMoved4();
      } else if (opcaoMenu == animacao6) { //"Desenho Livre
        mouseMoved6();
      } else if (opcaoMenu == animacao11) { //"Mini" Piano
        mouseMoved11();
      }
    }
    
    // Controles através do Mouse
    void mousePressed() {
      if (opcaoMenu == start) { //Menu Inicial
        if (menuAtivo == 1 ){ 
          for (Button but : buttonsMenu1) {
            but.press();
            if (but.pressed) validaBotaoMenu01(but);
          }
        } else if (menuAtivo == 2 ){  
          for (Button but2 : buttonsMenu2) {
            but2.press();
            if (but2.pressed) validaBotaoMenu02(but2);
          }
        }
      } else if (opcaoMenu == animacao2) { //Jogo Balões
        mousePressed2();
      } else if (opcaoMenu == animacao3) { //Desenha formas
        mousePressed3();
      } else if (opcaoMenu == animacao4) {  //"Espalhando tinta" /Paint
        mousePressed4();
      } else if (opcaoMenu == animacao6) { //Desenhando Formas
        mousePressed6();
      } else if (opcaoMenu == animacao7){
        mousePressed7();
      } else if (opcaoMenu == animacao8) { //"Desenha Formas
        mousePressed8();
      } else if (opcaoMenu == animacao9){  //Video - História o Sapo
        mousePressed9();
      } else if (opcaoMenu == animacao10) { //"Mini" Piano
        //
      } else if (opcaoMenu == animacao11) { //"Mini" Sintetizador
        //mousePressed11();
      } else if (opcaoMenu == animacao12) { //"Jogo" Bolas se chocando
        mousePressed12();
      }
    }
    
    //Controle ao Soltar Botão 
    void mouseReleased() {
      if (opcaoMenu == start) {            //Menu Inicial
        for (Button but : buttonsMenu1) {
          but.release();
        }
      } else if (opcaoMenu == animacao1) {  //Desenhando Bolhas
        mouseReleased1();
      } else if (opcaoMenu == animacao4) {  //Espalha "Tinta" /Paint
        //mouseReleased4();
      } else if (opcaoMenu == animacao6) {  //Desenhando Formas(*)
        mouseReleased6();
      } else if (opcaoMenu == animacao11) {  //"Mini" Piano
        //mouseReleased11();
      } else if (opcaoMenu == animacao12) {  //"Jogo" bolas se chocando
        mouseReleased12();
      }
    }
    
    void mouseClicked() {
      if (opcaoMenu == animacao8) {
        //mouseClicked8();
      } else if (opcaoMenu == animacao11) {
        mouseClicked11();
      }
    }
    
    //Controle para chamada de Programas, conforme botão pressionado 
    void validaBotaoMenu01(Button but) {
      if (but.index == 0) {        //01 - baloes
        setup1(); 
        opcaoMenu = animacao1;
      } else if (but.index == 1) { //02 - baloes_nuvens
        setup2(); 
        opcaoMenu = animacao2;
      } else if (but.index == 2) { //03 - Formas com Linhas
        setup3(); 
        opcaoMenu = animacao3;
        //println("Desenho Linhas ativado");
      } else if (but.index == 3) { //04 - "Espalhando tinta"
        setup4(); 
        opcaoMenu = animacao4;
      } else if (but.index == 4) { //05 - passaro
        setup5(); 
        opcaoMenu = animacao5;
      } else if (but.index == 5) { //05 - desenho 
        setup6(); 
        opcaoMenu = animacao6;
      } else if (but.index == 6) { //06 - piano
        setup7(); 
        opcaoMenu = animacao7;
      } else if (but.index == 7) { //07 - musica 
        setup8(); 
        opcaoMenu = animacao8;
      } else if (but.index == 9) { //08 - Teste 
        setup9(); 
        opcaoMenu = animacao9;
      } else if (but.index == 10) { //09 - Teste 
        //setup10(); 
        //opcaoMenu = animacao10;
      } else println ("Não Encontrado Indice do Botão (erro #002)");
    
      if (opcaoMenu > 0) habilitaDesabilitaBotoes();
      println("Index Menu 1: " + but.index);
    }
    
    //Controle para chamada de Programas ( Menu 2 ), conforme botão pressionado 
    void validaBotaoMenu02(Button but2) {
      if (but2.index == 0) {        //01 - Animação o Sapo não lava o Pé
        setup9(); 
        opcaoMenu = animacao9;
      } else if (but2.index == 2) { // "Mini" Sintetizador 
        setup11(); 
        opcaoMenu = animacao11;
      } else if (but2.index == 3) { // "Jogo" bolas se chocando 
        setup12(); 
        opcaoMenu = animacao12;
      } else if (but2.index == 4) { // "Esqueleto" Teste Kinect 
        background(255);
        r                  = 255;
        g                  = 255;
        b                  = 255;
        limpaTela          = true;
        usaKinect          = true;
        desenhaEsqueleto   = true;
        mostraImagemKinect = true;
        opcaoMenu          = 99; //Desenha "Esqueleto Kinect" ( Teste )
    
        btnAnterior.setVisible(false);
        btnProximo.setVisible(false);
      } else if (but2.index == 5) { // Desenha "Mão" pelo Leap Motion ( Teste _
        background(255);
        r                  = 255;
        g                  = 255;
        b                  = 255;
        limpaTela          = true;
        usaLeapMotion      = true;
        desenhaCursorM     = true;
        opcaoMenu          = 88; //Desenha "Esqueleto Kinect" ou "mão" Leap Motion
    
        btnAnterior.setVisible(false);
        btnProximo.setVisible(false);
      }
    
      if (opcaoMenu > 0) habilitaDesabilitaBotoes();
      println("Index Menu 2: " + but2.index);
    }
    
    //Controle pelo Teclado
    void keyPressed() {
      if (key == ESC) inicializaMenu();
    
      if (opcaoMenu == start){
        if (key==CODED) {
          if (keyCode == UP) mousePressed();
        }
      }
    
      if (opcaoMenu != animacao11) { //Se não for "Piano"
        //if (key == 'T' || key == 't') visualizaTexto       = !visualizaTexto; //Habilita/Desabilita controle para mostrar texto Informativo sobre dispositivos usados
        if (key == 'I' || key == 'i') mostraInfoDisp       = !mostraInfoDisp; //Habilita/Desabilita controle para mostrar Informações sobre dispositivos
        if (key == 'B' || key == 'b') limiteBola           = !limiteBola;     //Habilita/Desabilita controle para "explodir" bolas no limite das bordas da tela ( Ellipses )
        if (key == 'A' || key == 'a') usaEntradaAudio      = !usaEntradaAudio;
        if (key == 'R' || key == 'r') usaEntradaSerial     = !usaEntradaSerial;
        if (key == 'S' || key == 's') usaSom               = !usaSom;
        if (key == 'Q' || key == 'Q') desenhaEsqueleto     = !desenhaEsqueleto;
        if (key == 'D' || key == 'd') desenhaMaoDir        = !desenhaMaoDir;
        if (key == 'E' || key == 'e') desenhaMaoEsq        = !desenhaMaoEsq; 
        if (key == 'P' || key == 'p') rastreamentoSentado  = !rastreamentoSentado;
        if (key == 'U' || key == 'u') usuarioUnico         = !usuarioUnico;
      }
    
      if (key == 'K' || key == 'k'){ 
        usaKinect = !usaKinect;
        //if (usaKinect) cursor(HAND);
        //else cursor(CROSS);
      }
    
      if (key == 'L' || key == 'l'){
        usaLeapMotion = !usaLeapMotion;
        //cursor(HAND);
      }
    
      if (usaLeapMotion){
        //Muda tipo de rastreamento ( Mãos, dedos...)
        if (key == '1') 
          opcaoLeapMotion = 1;
        else if (key == '2') 
          opcaoLeapMotion = 2;
        else if(key == ' ')
          background(255);   
      }
    
      /*if (key == 'A' || key == 'a'){
        difMovimento = difMovimento + 2;
      } else if (key == 'D' || key == 'd'){
        difMovimento = difMovimento - 2;
      }*/
    
      /*if (usaKinect){
        println("Alterado forma de rastramento Kinect... " + key);
        if (key == '1') opcaoRastKinect = 1;      //Rastreamento "esqueleto" sentado
        else if (key == '2') opcaoRastKinect = 2; //Rastreamento somente das mãos
        else if (key == '3') opcaoRastKinect = 3; //Rastreamento somente dos dedos
        else if (key == '4') opcaoRastKinect = 4; //Rastreamento "esqueleto" em Pé
      }*/  
    
      if (opcaoMenu == animacao1) { //Desenhando Bolhas     
        keyPressed1();      
      } else if (opcaoMenu == animacao2){  //"Jogo" com Balões
        keyPressed2();
      } else if (opcaoMenu == animacao3) { //Desenhando Formas
        keyPressed3();
      } else if (opcaoMenu == animacao4) { //Desenhando com "Tinta"
        keyPressed4();
      } else if (opcaoMenu == animacao5){  
        keyPressed5();
      } else if (opcaoMenu == animacao6) { //Desenhando Formas(*)
        keyPressed6();
      } else if (opcaoMenu == animacao7){
        keyPressed7();
      } else if (opcaoMenu == animacao8) { //Desenha Formas
        keyPressed8();
      } else if (opcaoMenu == animacao9) {
        //keyPressed9();
      } else if (opcaoMenu == animacao11) {
        keyPressed11(9,9);
      } else if (opcaoMenu == 12) {
        keyPressed12(); 
      } 
    
      /*if (key == 'F' || key == 'f') { //Teste para FireWorks
        limpaTela    = true;
        opcFireWorks = 2;
        setup4();
        opcaoMenu = animacao0;
      }*/ 
    }
    
    void keyReleased() {
      if (opcaoMenu == animacao3) { //Desenha Formas
        keyReleased3();
      } else if (opcaoMenu == animacao6) {
        keyReleased6();
      } else if (opcaoMenu == animacao7) {
        keyReleased7();
      } else if (opcaoMenu == animacao9) {
        keyReleased9();
      } else if (opcaoMenu == animacao11) {
        keyReleased11();
      }
    }
    
  • edited July 2015

    if I understand you correctly you encounter side effects that you do not want.

    The (former separate) sketches (inside the mother sketch) influence each other what you don't want

    TfGuy44 made a great frame sketch for that issue.

    here each class can be seen as a program on its own.

    http://forum.processing.org/two/discussion/11573/a-new-class-state-how-to-tackle-bigger-programs

    quote:

    ..........If, however, I was going to write a more complex sketch, then, for the record, yes, I still like the inheriting approach better, for the simple reason that it also encapsulates the data associated with each state.

  • the approach is a little complex but :

    • each state has its own class

    • the state classes have each only one object (one state)

    • the states are stored in an ArrayList with the index "currentState" (which changes)

    • each state can have all the vars it needs within the class. So you minimize the global vars and the bad side effects

    • there are other classes like buttons outside the states. These other classes are not part of the approach really

  • Hello,

    The problem is the same (undesired side effect), when I run multiple sketches together, though each has the "setup" individual, it should be something in memory, I'm not knowing how to control ...

    I'll take a look at this other model, for how can adapt the project.

    Once again thank you ...

  • Hello guys,

    Continuing to research how to operate multiple sktches in a single project, I found this solution, which was adapted this link:

    forum.processing.org/two/discussion/10937/multiple-sketches

    The way I'm developing works well, but sometimes have some "side effects" when you run certain animations ...

    This otherwise found interesting, because each is actually separate.

    I need help on a detail, for example:

    When I perform a sketch, and opens a second frame (window) when you close the last open, closes the entire application.

    In exemploA, I'm trying to control it using controls on the ESC key.

    Someone would know if you have any other way to close only aa second open window, and let main (Menu) running?

    Another thing, I could create run-time window? I tried this, but did not, gives the message that the object needs to be started.

    Yet another detail, how do we "destroy" the window created after closing? I tried to use the destroy () method, but does not seem to work because when I call the window again, does not start setup () (called the window), but draw () is executed, but without the settings that are in setup ()

    I hope you can understand ...

    For now that's it, thank you from the attention,

    Thank you,

    Notes: Do not put the programs as images, are just examples, to ride the way will work.

    Código adaptado do exemplo:

    frames

    /**
     * Multiple Nested PApplets (v2.0)
     * by GoToLoop (2015/May/21)
     *
     * forum.processing.org/two/discussion/10937/multiple-sketches
     * forum.processing.org/two/discussion/7036/multiple-screens
     */
    
    import controlP5.*;
    private ControlP5 cp5;
    
    //Variáveis Públicas, para outras Frames ( Animações separadas )
    static int valor = 0;
    
    // Main PApplet Sketch:
    static final int FPS = 60, TOGGLE = 5*FPS; // 5 seconds
    //static final PApplet ExemploA, ExemploB, ExemploC; 
    
    static final PApplet ExemploA = new exemploA(), 
                         ExemploB = new exemploB(),
                         ExemploC = new exemploC();
    
    boolean limpaTela  = true;
    
    void setup() {
      //size(displayWidth, displayHeight-65, JAVA2D);
      size(500, 400, JAVA2D);
      smooth(4);
      frameRate(FPS);
    
      textFont(createFont("Serif", 32, true));
      textAlign(CENTER, CENTER); 
      fill(120, 20, 20);
    
      // Instantiating All Nested PApplet Sketches:
      String[] sketches = getSketchNestedClassNames();
    
      //for (String sketch : sketches)  main(sketch);
      printArray(sketches);
    
      //runSketch(new String[] { ARGS_FULL_SCREEN, "Full Window" }, another);
    
      cp5 = new ControlP5(this);
      criaObjetos(); //Cria Botões ( with Controp5 )
    }
    
    void draw() {
      if (limpaTela) background(255);
    }
    
    void keyPressed() {
      //int k = keyCode;
    
      //if (k == ENTER | k == RETURN)  activateSketch(another);
      //else if (k == ' ')             disableSketch(another);
      if (key == ESC )
        key = 0;
    
      println("Tecla Pressionada... ");
    }
    
    // Util Functions for Hiding/Displaying/Destroy Toggling Sketches:
    //public static final void disableSketch(PApplet p) {
    static final void disableSketch(PApplet p) {
      p.frame.hide();
      p.noLoop();
    }
    
    //public static final void activateSketch(PApplet p) {
    static final void activateSketch(PApplet p) {
      p.frame.show();
      p.loop();
    }
    
    static final void destroySketch(PApplet p) {
      //p.frame.destroy();
      p.destroy();
    }
    
    static final void toggleSketch(PApplet p) {
      boolean isActive = p.frame.isVisible();
      p.frame.setVisible(!isActive);
    
      if (isActive)  p.noLoop();
      else           p.loop();
    }
    
    // Util Functions for Nested PApplet Sketches:
    static final String getSketchClassName() {
      return Thread.currentThread().getStackTrace()[1].getClassName();
    }
    
    static final String[] getSketchNestedClassNames() {
      Class[] nested;
    
      try {
        nested = Class.forName(getSketchClassName()).getClasses();
      }
      catch (ClassNotFoundException cause) {
        throw new RuntimeException(cause);
      }
    
      int idx = 0, len = max(0, nested.length - 2);
      String[] classes = new String[len];
    
      while (idx != len)  classes[idx] = nested[idx++].getName();
      return classes;
    }
    
    void criaObjetos(){
      cp5.addButton("btn01")
         .setPosition(20,70)
         .setImages(loadImage("bolhas0.png"), loadImage("bolhas1.png"), loadImage("bolhas2.png"))
         .updateSize();
    
     cp5.addButton("btn02")
        .setPosition(150,70)
        .setImages(loadImage("bolha0.png"), loadImage("bolha1.png"), loadImage("bolha2.png"))
        .updateSize(); 
    
     cp5.addButton("btn03")
        .setPosition(270,70)
        .setImages(loadImage("boloes0.png"), loadImage("boloes1.png"), loadImage("boloes2.png"))
        .updateSize(); 
    }
    
    void btn01(int theValue) {
      //println("Acionado evento btn01 - Index: "+theValue);
      //ExemploA = new exemploA(); 
      runSketch(new String[] { "Exemplo A" }, ExemploA);
    }
    
    void btn02(int theValue) {
      //println("Acionado evento btn02 - Index: "+theValue);
      //ExemploB = new exemploB();
      runSketch(new String[] { "Exemplo B" }, ExemploB);
    }
    
    void btn03(int theValue) {
      //println("Acionado evento btn02 - Index: "+theValue);
      //ExemploC = new exemploC(); 
      runSketch(new String[] { "Exemplo C" }, ExemploC);
    }
    
    //Exemplo A
    // Nested PApplet Class A:
    public static final class exemploA extends PApplet {
      int valorA = 1;
      void setup() {
        //size(displayWidth, displayHeight-65, JAVA2D);
        size(400, 300, JAVA2D);
        background(255);
        smooth(4);
    
        textFont(createFont("SansSerif", 24, true));
        textAlign(CENTER, CENTER);
        fill(20, 120, 20);
        println("Iniciando Exemplo A");
      }
    
      void draw() {
        println("executando Exemplo A");
        background(200, 255, 200);
        //fill(0,0,255);
        //ellipse(mouseX, mouseY, 30, 30);
        translate(width>>1, height>>1);
        scale(.1 + sin(frameCount*.02), 1);
        text("Skecth Exemplo A ", 0, 0);
      }
    
      void keyPressed(){
        valor++; //Variável pública
        println("Tecla Pressionada em A... " + valor);  
    
        if (key == ESC ){
          key = 0;
    
          disableSketch(ExemploA);
          destroySketch(ExemploA);
        }
      }
    }
    
    //Exemplo B
    // Nested PApplet Class B:
    public static final class exemploB extends PApplet {
      /** 
       * Bouncy Words (v3.04)
       * by tfguy & jtwhite14 (2013/Aug)
       * mod GoToLoop
       * 
       * forum.processing.org/topic/animated-text
       * studio.processingtogether.com/sp/pad/export/ro.9eHY5Fel1e0Jr/latest
       */
    
      static final int NUM = 2;
      final BouncyWord[] words = new BouncyWord[NUM];
      int valorB = 2;
    
      void setup() {
        size(400, 250, JAVA2D);
        smooth(4);
    
        fill(BouncyWord.INK);
        textAlign(LEFT, CENTER);
    
        //textFont(createFont("Trebuchet MS Bold", BouncyWord.DIM, true));
    
        words[0] = new BouncyWord("Skecth Exemplo B", -1.5, 0, 50);
        words[1] = new BouncyWord("Test Multiple Sketchs", 2.3, 0, 100);
       //words[2] = new BouncyWord("Studio", -3, 0, 150);
    
       println("Iniciando Exemplo B");
      }
    
      void draw() {
        background(-1);
        for (BouncyWord w : words)  w.bounce();
      }
    
      void keyPressed(){
        println("Tecla Pressionada em B... " + valorB);   
      }
    
      class BouncyWord {
        static final short DIM = 90;
        static final color INK = 0100 << 030;
    
        String word;
        float px, py, vx, vy;
    
        BouncyWord(String iword, float ivy, float ipx, float ipy) {
          word = iword;
          vy = ivy;
          px = ipx;
          py = ipy;
        }
    
        void bounce() {
          if ((py += vy) >= height - (DIM>>2) | py < (DIM>>2))  vy *= -1;
          text(word, px, py);
        }
      }
    }
    
    //Exemplo C
    // Nested PApplet Class A:
    public static final class exemploC extends PApplet {
      int valorC = 3;
      void setup() {
        size(300, 150, JAVA2D);
        smooth(4);
    
        textFont(createFont("SansSerif", 24, true));
        textAlign(CENTER, CENTER);
        fill(20, 120, 20);
        println("Iniciando Exemplo C");
      }
    
      void draw() {
        background(200, 255, 200);
        translate(width>>1, height>>1);
        scale(.1 + sin(frameCount*.02), 1);
        text("Teste Exemplo C", 0, 0);
      }
    
      void keyPressed(){
        println("Tecla Pressionada em C... " + valorC);  
        //if (key == ESC ) disableSketch(AnotherSketch);
      }
    }
    
  • Hello guys,

    Still with the matter of using multiple sketches, I am trying to adapt this other model, but still has a detail that I'm unable to solve, I will try to explain.

    When I call a particular option for a second time does not run the setup () function.

    That is, the first works normal, if another access option and return the previous, the setup () function is not loaded, and it affects the performance in draw ();

    I've tried to create another function on Extended Applet (setupBall eg using public static void ...) but can not access, the Skecth where the menu.

    Any idea how to fix this?

    Below the print screens as is getting the project, and a snippet (not put all because it is getting a little long).Menu Sketchs Paint musica

    /*
     * Multiple Sketchs
     * Fonte: Forum Processing
     *            OpenProcessing
    */
    
    import controlP5.*;
    private ControlP5 cp5;
    
    // Main PApplet Sketch:
    static final int FPS = 60, TOGGLE = 5*FPS; // 5 seconds
    static int opcaoDesenho = 1; //Controle para mudar de Animação, na mesma tela
    
    //static final PApplet ExemploA, ExemploB, ExemploC; 
    static final PApplet ExemploA = new exemploA(), 
                         ExemploB = new exemploB(),
                         PlaySom  = new playSom();
    
    //pathGlobalDefault: set path or use "" to use data path of the sketch  
    static String pathGlobalDefault = "D://Musicas//";
    static String pathGlobalHome    = "D://Musicas//Diversos//";                  
    
    boolean limpaTela  = true;
    
    PFont fontA;     //Define variável para controle de tamanho de Fonte
    PFont boldFontA; //Define fonte Negrito
    
    void setup() {
      //size(500, 400, JAVA2D);
      size(displayWidth, displayHeight-65, JAVA2D);
      smooth(4);
      cursor(HAND);
      frameRate(FPS);
    
      //Título da aplicação na Janela do Windows
      frame.setTitle("C.A.L. Anima - Animação - Interação");
    
      //Define fonte para o Texto e seta cor
      fontA     = loadFont("BuxtonSketch-48.vlw");  
      boldFontA = loadFont("Candara-BoldItalic-48.vlw");
      textFont(fontA, 40);
      fill(#1273C1); 
    
      cp5 = new ControlP5(this);
      criaObjetos(); //Cria Botões ( with Controp5 )
    }
    
    void draw() {
      if (limpaTela) background(255);
    
      textFont(fontA, 40);
      fill(#1273C1);
      text("Selecione uma Opção para Começar...", 10, 30);
    }
    
    void keyPressed() {
      if (key == ESC ) key = 0;
      //println("Tecla Pressionada... ");
    }
    
    // Util Functions for Hiding/Displaying/Destroy Toggling Sketches:
    //public static final void disableSketch(PApplet p) {
    static final void disableSketch(PApplet p) {
      p.frame.hide();
      p.noLoop();
    }
    
    //public static final void activateSketch(PApplet p) {
    static final void activateSketch(PApplet p) {
      p.frame.show();
      p.loop();
    }
    
    static final void destroySketch(PApplet p) {
      //p.frame.destroy();
      p.destroy();
      //p.frame.exit();
      //p.frame.dispose();
    }
    
    static final void toggleSketch(PApplet p) {
      boolean isActive = p.frame.isVisible();
      p.frame.setVisible(!isActive);
    
      if (isActive)  p.noLoop();
      else           p.loop();
    }
    
    //static final void verificaApplet(PApplet p) {
    boolean verificaApplet(PApplet p) {
      boolean isActive = p.frame.isVisible();
      //p.frame
      println("Estado da Applet : " + isActive);
    
      //if (isActive) setupBalls();
      return (isActive);
    }
    
    void btn01(int theValue) {
      //println("Acionado evento btn01 - Index: "+theValue);
      //ExemploA = new exemploA(); 
      runSketch(new String[] { "Desenhando Bolhas" }, ExemploA);
      verificaApplet(ExemploA);
    }
    
    void btn02(int theValue) {
      //println("Acionado evento btn02 - Index: "+theValue);
      //ExemploB = new exemploB();
      runSketch(new String[] { "Paint" }, ExemploB);
    }
    
    void btn03(int theValue) {
      //println("Acionado evento btn02 - Index: "+theValue);
      //ExemploC = new exemploC(); 
      runSketch(new String[] { "Musicas" }, PlaySom);
    }
    
    void criaObjetos(){
      cp5.addButton("btn01")
         .setPosition(50,(height/2)-100)
         .setImages(loadImage("bolhas0.png"), loadImage("bolhas1.png"), loadImage("bolhas2.png"))
         .updateSize();
    
     cp5.addButton("btn02")
        .setPosition(180,(height/2)-100)
        .setImages(loadImage("paint0.png"), loadImage("paint1.png"), loadImage("paint2.png"))
        .updateSize(); 
    
     cp5.addButton("btn03")
        .setPosition(300,(height/2)-100)
        .setImages(loadImage("musica0.png"), loadImage("musica1.png"), loadImage("musica2.png"))
        .updateSize(); 
    }
    
    //Code Classe Extends
    
    public static final class exemploA extends PApplet {
      /* OpenProcessing Tweak of *@*http://www.openprocessing.org/sketch/9793*@* */
      /* !do not delete the line above, required for linking your tweak if you upload again */
      //import sms.*;
    
      ParticleSystem ps;
      boolean showVectors = false;
    
      void setup(){
        //size(600, 600, P3D);
        size(displayWidth, displayHeight-65, JAVA2D);
        setupBalls();
      }
    
      public void setupBalls(){
        ps = new ParticleSystem(1, new PVector(width/2, height/2,0));
        //smooth();
      }
    
      void draw(){
        background(255);
    
        PVector G = new PVector(mouseX - width/2,mouseY - height/2);
        //PVector G = new PVector(-Unimotion.getSMSX(),Unimotion.getSMSZ());
        G.normalize();
    
        ps.gravity = G.get();
        ps.run();
        ps.addParticle();
      }
    
  • size in a class is not allowed

      size(displayWidth, displayHeight-65, JAVA2D);
    

    line 147

    size() should be used only once in your sketch (in line 30)

  • general I would recommend to work with states.

  • meaning:

    use int currentState = 0;

    in btn01, btn02 etc. you want to set currentState to 0,1 etc. and you want to call the setup of each class

      states.get(currentState).setup();
    

    in draw() you say:

    (set currentState=1000;in setup())

    void draw() {
      if (limpaTela) background(255);
    
    
    if (currentState==1000) {
          textFont(fontA, 40);
          fill(#1273C1);
          text("Selecione uma Opção para Começar...", 10, 30);
    }
    else
    {
          states.get(currentState).draw();
    
    }
    }
    

    compare to TFGuy44 first answer in http://forum.processing.org/two/discussion/11573/a-new-class-state-how-to-tackle-bigger-programs )

  • edited August 2015

    In order to avoid an all-green posted code in this forum, always use /** instead of /*! :-\"

  • Hello Chrisir,

    Thanks for the tips, I'll check best how to solve this ...

    I could "destroy" the applet, and recreating every time you call?

    instead of doing it at the beginning:

    static final PApplet ExemploA = new exemploA(), 
                         ExemploB = new exemploB(),
                         PlaySom  = new playSom();
    

    I would like to do so: static final PApplet ExemploA, ExemploB, ExemploC;

    And then create when actually call each option.

    void btn01(int theValue) {
      ExemploA = new exemploA(); 
      runSketch(new String[] { "Paint" }, ExemploA);
      //verificaApplet(ExemploA);
    }
    

    What about the code, mentioned by GoToLoop, I understand, to again place as directed.

    Many thanks again ...

  • More detail

    Before attempting this solution was commenting, I would also like to try to understand a detail when instantiates several sketches.

    I tried to "destroy" the instance, but it seems not work as I expected because it still created.

    Call to "destroy"

        void keyPressed() {
            if (key == ESC ){
              key        = 0;
              configurar = true;
              disableSketch(ExemploA);
              destroySketch(ExemploA);
            }
        }
    

    Function used, as in the previous example Forum:

    static final void disableSketch(PApplet p) {
      p.frame.hide();
      p.noLoop();
    }
    
    static final void destroySketch(PApplet p) {
      //p.frame.destroy();
      p.destroy();
      //p.frame.exit();
      //p.frame.dispose();
    }
    
  • no...

    don't use the destroy thing

    you can also use the normal way to instantiate the objects

    my point was to use setup() so you can make a clean stage at the starting of each state / object and also have a clean clear draw() as I've shown

  • Before changing as suggested, I would try something else (I'm really stubborn ... rsss)

    The problem does not appear in Call of ControlP5 Library button, I used them, just to let the simplest example, but other means of work, with the Button class that was passed in the first model, it works perfectly well ...

    We made some adaptations and then I will continue using this library to create buttons, because it facilitates to create various menus.

    Button class code before passing (adapted some details) ...

    //Class Button
    class Button {
      int x, y;                // The x- and y-coordinates
      int sizeW, sizeH;        // Dimension (width and height)
      color baseButton;        // Default gray value
      color overButton;        // Value when mouse is over the button
      color pressButton;       // Value when mouse is over and pressed
      boolean over    = false; // True when the mouse is over
      boolean pressed = false; // True when the mouse is over and pressed
      int index;               // index 
      PImage img1;             // image (1)
      PImage img2;             // image (2)
      PImage img3;             // image (3)
      PImage imgInfo;          // image (4)
      boolean mostraInfo;      // Controle para mostrar ou não informação ao passar o mouse sobre a figura
      boolean tempoAut;         // Controle para Click automatico, conforme tempo sobre o botão
    
      //The constructor (the underscore _ says I'm temp)
      Button(int _xP, int _yP, int _sW,  int _sH, int _index, PImage _img1, PImage _img2, PImage _img3, PImage _imgInfo, boolean _mostraInfo, boolean _tempoAut) {
        x          = _xP;
        y          = _yP;
        sizeW      = _sW;
        sizeH      = _sH;
        index      = _index;
        img1       = _img1;
        img2       = _img2;
        img3       = _img3;
        imgInfo    = _imgInfo;
        mostraInfo = _mostraInfo;
        tempoAut   = _tempoAut;
      }// the constructor 
    
      //Updates the over field every frame
      boolean update() {
        //println("Posicoes mouseX/mouseY - X/Y: " + mouseX + " - " + mouseY + " - " + x + " - " + y);
        if ((mouseX >= x) && (mouseX <= x + sizeW) && 
            (mouseY >= y) && (mouseY <= y + sizeH)){
          over = true;
          //txaInfo01.setVisible(true);
        }else{
          over = false;
          //txaInfo01.setVisible();
        }
    
        return over;
    
      }//Updates
    
      boolean press() {
        if (over == true) {
    
          //int passedTime = millis() - savedTime;
    
          //if (passedTime > 1000) {
            pressed   = true; 
          //  savedTime = millis(); // Save the current time to restart the timer!
          //}
          return true;
        }else{
          pressed = false;
          return false;
        }
      }//Press
    
      void release() {
        pressed = false; //Set to false when the mouse is released
        //over    = false; //Retirado devido ficar com efeito "over" mesmo depois que retornou ao Menu Inicial
      }//Release
    
      void display() {
        if (over) {
          image(img2, x, y);
          if (mostraInfo) image(imgInfo, 410, (height/2)+70);
    
          if (tempoAut){
            int passedTime = millis() - savedTime;
            if (passedTime > totalTime) {
              mousePressed();
              background(255);
              savedTime = millis(); // Save the current time to restart the timer!
            }
          }
        } else if (pressed){ 
          image(img3, x, y);
        } else{ 
          image(img1, x, y);
        }
     }//Display
    }//Class Button
    

    //Structure mount Menu:

            void criaMenu01() {
              String[][] objBut; 
              String posAlt = Integer.toString((height/2)-50); 
    
              int numBut = 8;  //Controle da quantidade de botões a serem criados
              objBut     = new String[][] { {"baloes",        "100", "105",   "50", posAlt, "2", "1"},   //01 
                                            {"baloes_nuvens", "100", "105",  "200", posAlt, "2", "1"},   //02
                                            {"formas_00_",    "100", "105",  "350", posAlt, "2", "1"},   //03
                                            {"pintura",       "100",  "90",  "500", posAlt, "2", "1"},   //04
                                            {"passaro",       "100", "105",  "650", posAlt, "2", "1"},   //05
                                            {"desenho",       "100", "105",  "800", posAlt, "2", "1"},   //06
                                            {"pencil_cursor", "100", "105",  "950", posAlt, "2", "1"},   //07  
                                            {"formas_02_",    "100", "105", "1100", posAlt, "2", "1"} }; //08
    
              //buttons = new Button[objButoon.length]; //Cria Array para botões a partir da Classe Button, conforme quantidade no elementos no Array objButoon
          buttonsMenu1 = new Button[numBut]; //Cria Array para botões a partir da Classe Button, conforme quantidade no elementos no Array objButoon
          carregaBotoes(numBut, 10, objBut, buttonsMenu1, true, tempoAutClick); //Chama funções para carregar botões, montando o Menu Inicial.
        }
    

    //Buttons function call

    void carregaBotoes(int numButtons, int spaceButton, String[][] objButoon, Button[] buttons, boolean mostraInfo, boolean tempoAut) {
      /** Parametros função carregaBotes: 1, Quantidade de botoes a serem criados.
          2, espaçamento entre os botões.
          3, array como nome dos botoes e demais refererencias para serem criados.
          4, Objeto Button passado como parâmetro, para ser válido de qualquer ponto de chamada.                 
      **/
    
      boolean opcRandomicoX, opcRandomicoY; //Variáveis para controle se o posicionamento é randomico
      int espacoBtn;
    
       PImage[] imageInfo = new PImage[numButtons];
      //carregaTextoInfo();
    
      //Objeto para reordenar Array, com posições X e Y para os Objetos
      IntList posicoesX, posicoesY;
    
      posicoesX = new IntList();
      posicoesY = new IntList();
    
      for (int k = 0; k < numButtons; k++) {
        posicoesX.append(int(objButoon[k][3]));
        posicoesY.append(int(objButoon[k][4]));
      } 
    
      posicoesX.shuffle();
      posicoesY.shuffle();
      //println(posicoesX);
      //println(posicoesY);
    
      //Carrega imagens conforme quantidade no Array, em seguida cria botões
      for (int i = 0; i < numButtons; i++) {
        //println("Imagem/ Valor de i: " + objButoon[i][0] + " - " + i );
        PImage[] images = new PImage[3];
    
        //Carrega imagens referente a informações de como funciona a animação
        imageInfo[i] = loadImage("Info_" + trim(str(menuAtivo)) + "_" + trim(str(i)) + ".png");
    
        //Carrega imagens para exibição conforme estado do botão ( normal, sobre, "click" )
        for (int j = 0; j < 3; j++) {
          //println("Imagem/ Valor de j: " + objButoon[i][0] + " - " + j);
          images[j] = loadImage(objButoon[i][0] + trim(str(j)) + ".png");
          images[j].resize(int(objButoon[i][1]), int(objButoon[i][2]));
        } 
    
        //Controle se posição X é randomico 
        if (objButoon[i][5] == "2") opcRandomicoX = true; 
        else opcRandomicoX = false;
    
        //Controle se posição Y é randomico 
        if (objButoon[i][6] == "2") opcRandomicoY = true; 
        else opcRandomicoY = false;
    
        //Validação para posicionar primeiro botão mais ao todo da tela
        if (i > 0) espacoBtn = spaceButton; 
        else espacoBtn = 5; 
    
        //Instancia objetos botões deixando disponível para uso ( Cria botões conforme parametros referente aos botões ).
        //buttons[i] = new Button(opcRandomico? int(random(height-200)): int(objButoon[i][3]), i+spaceButton+45,
        buttons[i] = new Button(opcRandomicoX? posicoesX.get(i)+espacoBtn: int(objButoon[i][3])+espacoBtn, 
                                opcRandomicoY? posicoesY.get(i)+espacoBtn: int(objButoon[i][4])+espacoBtn, 
                                int(objButoon[i][1]), int(objButoon[i][2]), 
                                i, 
                                images[0], images[1], images[2],
                                imageInfo[i],
                                mostraInfo,
                                tempoAut);
      }
    }
    

    Anyway, I put more code to get an idea, how to create the menu can be optional, the biggest problem is to separate the Scketchs, I will keep trying this model, it does not work, try the other that was suggested.

    If you can give some hint has "really like to destroy" the instance created applet (sketch) and always create again when called, would be helpful.

    Thank you again.

  • sorry I haven't really done this ControlP5 plus multiple sketches thing

    but anyway sure you can destroy your instance

  • Sorry ...

    I did not understand what to say had tried to work with states ...

    No way I really wanted to speak English at these times (thankfully google translator helps me) ... I will analyze better, then I put the results here.

    Thanks.

  • you're welcome.

  • edited August 2015

    @Jose_Aparecido, dunno enough of Processing's innards as to properly destroy() a PApplet, sorry!
    However, dunno why frame.hide() & noLoop() wouldn't be enough for ya either! (:|

  • Hello guys,

    So frame.hide () & noLoop () solves the problem to some extent, because I can see at the right time as choose the option.

    The problem is when I come running when I go out, have some "effects" collateral, and does not work as the first time you called.

    Below is an print from one of the options when you run the first time, and the second (appears some arrows, I do not know where you are doing it), if I run a third time back to normal, like the first time you ran, and so on ...

    So I figured if created at the time of the call, and then destroy, thus solve the problem.

    //Run the first time

    Primeiro

    //Run the second time

    segundo

    Got a way to call the setup complement () ... (but made even gambiarra ... rsss ...), but it seems that the problem is not to have called setup (), but something else, which still I do not know what can be, though each sketch is in separate instances.

    I'll keep trying here ...

    Thank you,

    att,

  • this seems to be a feature within the initial sketch

    post the source here pls (url to openprocessing or code)

    try finding the lines

    try to set the boolean var off in constr of that state

  • sorry I haven't really done this ControlP5 plus multiple sketches thing

    but anyway sure you can destroy your instance

    hummm... vou fazer sem o ControlP5, pra ver ser tem diferença... depois posto aqui...

    Obrigado novamente,

  • ops was wrong, I took part in Portuguese, sorry ...

    I will do without the ControlP5, to see has the difference ... then post here ...

    Thank you again,

  • This is the code I adapted, with sample forum with multipos sketches, and the animation OpenProcessing.

    //Program Menu

    /**
     * Multiple Sketchs
     * Fonte: Forum Processing
    **/
    
    import controlP5.*;
    private ControlP5 cp5;
    
    // Main PApplet Sketch:
    static final int FPS = 60, TOGGLE = 5*FPS; // 5 seconds
    static int opcaoDesenho = 1; //Controle para mudar de Animação, na mesma tela
    
    //static final PApplet ExemploA, ExemploB, ExemploC; 
    static final PApplet ExemploA = new exemploA(), 
                         ExemploB = new exemploB(),
                         PlaySom  = new playSom();
    
    //pathGlobalDefault: set path or use "" to use data path of the sketch  
    static String pathGlobalDefault = "D://Musicas//";
    static String pathGlobalHome    = "D://Musicas//Diversos//";                  
    
    static boolean limpaTela  = true; //Controle para Limpar a Tela, conforme opção
    static boolean configurar = true; //Controle para executar Setup 
    
    PFont fontA;     //Define variável para controle de tamanho de Fonte
    PFont boldFontA; //Define fonte Negrito
    
    void setup() {
      //size(500, 400, JAVA2D);
      size(displayWidth, displayHeight-65, JAVA2D);
      smooth(4);
      cursor(HAND);
      frameRate(FPS);
    
      //Título da aplicação na Janela do Windows
      frame.setTitle("C.A.L. Anima - Animação - Interação");
    
      //Define fonte para o Texto e seta cor
      fontA     = loadFont("BuxtonSketch-48.vlw");  
      boldFontA = loadFont("Candara-BoldItalic-48.vlw");
      textFont(fontA, 40);
      fill(#1273C1); 
    
      cp5 = new ControlP5(this);
      criaObjetos(); //Cria Botões ( with Controp5 )
    }
    
    void draw() {
      //if (configurar){
        if (limpaTela) background(255);
    
        textFont(fontA, 40);
        fill(#1273C1);
        text("Selecione uma Opção para Começar...", 10, 30);
        //println("Status execução: " + executando);
      //}
    }
    
    void keyPressed() {
      if (key == ESC ) key = 0;
      //println("Tecla Pressionada... ");
    }
    
    // Util Functions for Hiding/Displaying/Destroy Toggling Sketches:
    //public static final void disableSketch(PApplet p) {
    static final void disableSketch(PApplet p) {
      p.frame.hide();
      p.noLoop();
    }
    
    //public static final void activateSketch(PApplet p) {
    static final void activateSketch(PApplet p) {
      p.frame.show();
      p.loop();
    }
    
    static final void destroySketch(PApplet p) {
      //p.frame.destroy();
      p.destroy();
      //p.frame.exit();
      //p.frame.dispose();
    }
    
    static final void toggleSketch(PApplet p) {
      boolean isActive = p.frame.isVisible();
      p.frame.setVisible(!isActive);
    
      if (isActive)  p.noLoop();
      else           p.loop();
    }
    
    //static final void verificaApplet(PApplet p) {
    boolean verificaApplet(PApplet p) {
      boolean isActive = p.frame.isVisible();
      //p.frame
      println("Estado da Applet : " + isActive);
    
      //if (isActive) setupBalls();
      return (isActive);
    }
    
    void btn01(int theValue) {
      println("Acionado evento btn01 - Index: "+theValue);
      //ExemploA = new exemploA(); 
      try{
        noLoop();
        runSketch(new String[] { "Desenhando Bolhas" }, ExemploA);
        verificaApplet(ExemploA);
      }finally{
       loop(); 
      }
    }
    
    void btn02(int theValue) {
      println("Acionado evento btn02 - Index: "+theValue);
      //ExemploB = new exemploB();
      runSketch(new String[] { "Paint" }, ExemploB);
    }
    
    void btn03(int theValue) {
      println("Acionado evento btn02 - Index: "+theValue);
      //ExemploC = new exemploC(); 
      runSketch(new String[] { "Musicas" }, PlaySom);
    }
    
    void criaObjetos(){
      cp5.addButton("btn01")
         .setPosition(50,(height/2)-100)
         .setImages(loadImage("bolhas0.png"), loadImage("bolhas1.png"), loadImage("bolhas2.png"))
         .updateSize();
    
     cp5.addButton("btn02")
        .setPosition(180,(height/2)-100)
        .setImages(loadImage("paint0.png"), loadImage("paint1.png"), loadImage("paint2.png"))
        .updateSize(); 
    
     cp5.addButton("btn03")
        .setPosition(300,(height/2)-100)
        .setImages(loadImage("musica0.png"), loadImage("musica1.png"), loadImage("musica2.png"))
        .updateSize(); 
    }
    
    // Util Functions for Nested PApplet Sketches:
    /*static final String getSketchClassName() {
      return Thread.currentThread().getStackTrace()[1].getClassName();
    }
    
    static final String[] getSketchNestedClassNames() {
      Class[] nested;
    
      try {
        nested = Class.forName(getSketchClassName()).getClasses();
      }
      catch (ClassNotFoundException cause) {
        throw new RuntimeException(cause);
      }
    
      int idx = 0, len = max(0, nested.length - 2);
      String[] classes = new String[len];
    
      while (idx != len)  classes[idx] = nested[idx++].getName();
      return classes;
    
      ////// Parte que estava em Setup()
       // Instantiating All Nested PApplet Sketches:
      //String[] sketches = getSketchNestedClassNames();
    
      //for (String sketch : sketches)  main(sketch);
      //printArray(sketches);
    
      //runSketch(new String[] { ARGS_FULL_SCREEN, "Full Window" }, another);
    }*/
    

    //Program Animation

        public static final class exemploA extends PApplet {
          /* OpenProcessing Tweak of *@*http://www.openprocessing.org/sketch/9793*@* */
          /* !do not delete the line above, required for linking your tweak if you upload again */
          //import sms.*;
    
          ParticleSystem ps;
          boolean showVectors = false;
    
          void setup(){
            //size(600, 600, P3D);
            size(displayWidth, displayHeight-65, JAVA2D);
            setupBalls();
          }
    
          public void setupBalls(){
            ps = new ParticleSystem(1, new PVector(width/2, height/2,0));
            //smooth();
            println("Executando SetupBalls");
          }
    
          void draw(){
            if (configurar){
              setupBalls();
              configurar = false;
            }
    
            background(255);
    
            PVector G = new PVector(mouseX - width/2,mouseY - height/2);
            //PVector G = new PVector(-Unimotion.getSMSX(),Unimotion.getSMSZ());
            G.normalize();
    
            ps.gravity = G.get();
            ps.run();
            ps.addParticle();
          }
    
          void keyPressed() {
            if (key == ESC ){
              key        = 0;
              configurar = true;
              disableSketch(ExemploA);
              destroySketch(ExemploA);
            }
            showVectors = !showVectors;
          }
    
          class Particle {
            PVector loc;
            PVector vel;
            PVector acc;
    
            color c;
            int radio;
    
            float bounce = 0.8;
            float timer;
            float mass;
            boolean colliding = false;
            PImage img;
            int vez = 0;
    
            Particle(PVector setLoc){
              loc = setLoc.get();
              vel = new PVector(random(-2,2),random(-2,2));
              acc = new PVector(random(-2,2),random(-2,2));
    
              radio = (int)random(3,10);
              mass = radio/2;
    
              c = color(random(0,255),random(0,255),random(0,255));
    
              timer = 255;
    
              img = null;
              vez++;
              println("Iniciando 1 ... " + vez );
            }
    
            Particle(PVector setLoc, PImage setImg){
    
              loc = setLoc.get();
              vel = new PVector(random(-2,2),random(-2,0));
              acc = new PVector(0,0);
    
              radio = (int)random(3,10);
    
              mass = radio/2;
    
              c = color(random(0,255),random(0,255),random(0,255));
    
              timer = 255;
    
              img = setImg;
              //println("Iniciando 2 ...");
            }
    
            void go(){
              update();
              checkBordes();
              render();
            }
    
            void update(){
              vel.add(acc);
              loc.add(vel);
              acc.mult(0);
              timer -= 1.0;
            }
    
            void drawShape(){
              if (img == null) {
                fill(red(c),green(c),blue(c),timer);
                noStroke();
                ellipse(loc.x,loc.y,radio*2,radio*2);
              } else {
                imageMode(CENTER);
                fill(red(c),green(c),blue(c),timer);
                image(img,loc.x,loc.y,radio,radio);
              }
            }
    
            void render(){
              drawShape();
    
              if (showVectors) {
                drawVector(vel,loc,10);
                //drawVector(G,loc,100);
              }
            }
    
            boolean dead(){
              if (timer <= 0.0){
                return true;
              } else {
                return false;
              }  
            }
    
            void checkBordes(){
              if (loc.y + radio >= height){
                loc.y = height - radio;
                vel.y *= -bounce;
              }
    
              if (loc.y - radio <= 0) {
                loc.y = radio;
                vel.y *= -bounce;
              }
    
    
              if(loc.x + radio >= width){
                loc.x = width - radio;
                vel.x *= -bounce;
              }
    
              if (loc.x - radio <= 0){
                loc.x = radio;
                vel.x *= -bounce;
              }
            }
    
            void applyForce(PVector force){
              force.div(mass);
              acc.add(force);
            }
    
            PVector calcGravForce(Particle p){
              PVector dir = PVector.sub(loc,p.loc);
              float d = dir.mag();
              //d = constrain(d,5.0,25.0);
              dir.normalize();
              float force = (9.8 * radio * p.radio) / (d * d);
              dir.mult(force);
              return dir;
            }
    
            void collideEqualMass(Particle p) {
              float d = PVector.dist(loc,p.loc);
              float sumR = radio + p.radio;
              // Are they colliding?
              if (!colliding && d < sumR) {
                // Yes, make new velocities!
                colliding = true;
                // Direction of one object to another
                PVector n = PVector.sub(p.loc,loc);
                n.normalize();
    
                // Difference of velocities so that we think of one object as stationary
                PVector u = PVector.sub(vel,p.vel);
    
                // Separate out components -- one in direction of normal
                PVector un = componentVector(u,n);
                // Other component
                u.sub(un);
                // These are the new velocities plus the velocity of the object we consider as stastionary
                vel = PVector.add(u,p.vel);
                p.vel = PVector.add(un,p.vel);
              } else if (d > sumR) {
                colliding = false;
              }
            }
          }
    
          class ParticleSystem {
            PVector gravity = new PVector(0,9.8);
    
            ArrayList particles;
            PVector origin;
    
            float t = 0;
    
            PImage img = null;
    
            boolean bouncing = false;
    
            ParticleSystem(int num, PVector v){
              particles = new ArrayList();
              origin = v.get();
              for(int i = 0; i < num; i++){
                particles.add(new Particle(origin));
              }
            }
    
            void run(){
              for(int i = particles.size()-1; i >= 0; i--){
                Particle p = (Particle) particles.get(i);
    
                if (bouncing) {
                  for(int a = 0; a < particles.size(); a++){
                    if(a != i){
                      Particle pa = (Particle) particles.get(a);
                      p.collideEqualMass(pa);
                    }
                  } 
                }
    
                PVector G = gravity.get();
    
                p.applyForce(G);
                p.go();
    
                if (p.dead()){
                  particles.remove(i);
                }
              }
              t += 0.7;
            }
    
            void addParticle(){
              particles.add(new Particle(origin,img));
            }
    
            void addParticle(Particle p){
              particles.add(p);
            }
    
            boolean dead(){
              if (particles.isEmpty()){
                return true;
              } else {
                return false;
              }
            }
          }
    
          void drawVector(PVector v, PVector loc, float scayl) {
            pushMatrix();
            float arrowsize = 4;
            // Translate to location to render vector
            translate(loc.x,loc.y);
            stroke(0);
    
            // Call vector heading function to get direction (note that pointing up is a heading of 0) and rotate
            rotate(v.heading2D());
    
            // Calculate length of vector & scale it to be bigger or smaller if necessary
            float len = v.mag()*scayl;
    
            // Draw three lines to make an arrow (draw pointing up since we've rotate to the proper direction)
            line(0,0,len,0);
            line(len,0,len-arrowsize,+arrowsize/2);
            line(len,0,len-arrowsize,-arrowsize/2);
            popMatrix();
          }
    
          PVector componentVector (PVector vector, PVector directionVector) {
            //--! ARGUMENTS: vector, directionVector (2D vectors)
            //--! RETURNS: the component vector of vector in the direction directionVector
            //-- normalize directionVector
            directionVector.normalize();
            directionVector.mult(vector.dot(directionVector));
            return directionVector;
          }
    
          /*int valorA = 1;
          void setup() {
            //size(displayWidth, displayHeight-65, JAVA2D);
            size(400, 300, JAVA2D);
            background(255);
            smooth(4);
    
            textFont(createFont("SansSerif", 24, true));
            textAlign(CENTER, CENTER);
            fill(20, 120, 20);
            println("Iniciando Exemplo A");
          }
    
          void draw() {
            println("executando Exemplo A");
            background(200, 255, 200);
            //fill(0,0,255);
            //ellipse(mouseX, mouseY, 30, 30);
            translate(width>>1, height>>1);
            scale(.1 + sin(frameCount*.02), 1);
            text("Skecth Exemplo A ", 0, 0);
          }
    
          void keyPressed(){
            valor++; //Variável pública
            println("Tecla Pressionada em A... " + valor);  
    
            if (key == ESC ){
              key = 0;
    
              disableSketch(ExemploA);
              //destroySketch(ExemploA);
            }
          }*/
        }
    

    Thank you for equanto again tomorrow still here ...

  • Sorry, I forgot to schedule correctly, turned green, where it should not ...

  • edited August 2015

    As I already tipped ya: "Replace every /* w/ /**!
    Please, check your Portuguese to English auto-translations!
    Even better, post both languages so we can have a better chance to figure it out harder parts!

  • I'm sorry again, it was an error even when it comes to copy and paste ... I'll be more careful.

    Thanks,

  • Remember that we can always "Edit" our posts! ;;)

  • OK,

    Have a nice day!

  • Hello again,

    The code that I put before will not work, was missing parts ... I'm putting another with two options working, thus giving to get a better idea of what is happening ...

    Recalling, in "Balls" animation, when you enter the first time, is OK, the second time running, arrows appear in the animation ... is executed again, it is OK ...

    As for the "Paint", when you run the second time, change the background color, so I realized the second time does not run the setup () function frame created (Extended), when he called again, just draw () function is performed, of course, because setup () only runs when the sketch is created ...

    Need to see a way around it, I tried to do something in exemploA, but still not ideal.

    If they can analyze the code and give some hint of what might be happening, it would be helpful.

    Once again thank you all ...

    Project code (You need to create source in the Local Machine)

    Observations: I'll separate programs due exceeds the limit for posting

        /**
         * Multiple Sketchs
         * Source: Forum Processing
         *         Links: http://forum.processing.org/two/discussion/comment/41926#Comment_41926
         *                http://forum.processing.org/two/discussion/10937/multiple-sketches
         *         OpenProcessing
         *         Others also...
        **/
    
        import controlP5.*;
        private ControlP5 cp5;
    
        // Main PApplet Sketch:
        static final int FPS = 60, TOGGLE = 5*FPS; // 5 seconds
        static int opcaoDesenho = 1; //Controle para mudar de Animação, na mesma tela
    
        //static final PApplet ExemploA, ExemploB; 
        static final PApplet ExemploA = new exemploA(),
                             ExemploB = new exemploB();
    
        //                     PlaySom  = new playSom();
    
        //pathGlobalDefault: set path or use "" to use data path of the sketch  
        static String pathGlobalDefault = "D://Musicas//";
        static String pathGlobalHome    = "D://Musicas//Diversos//";                  
    
        static boolean limpaTela  = true; //Controle para Limpar a Tela, conforme opção
        static boolean configurar = true; //Controle para executar Setup 
    
        PFont fontA;     //Define variável para controle de tamanho de Fonte
        PFont boldFontA; //Define fonte Negrito
    
        void setup() {
          //size(500, 400, JAVA2D);
          size(displayWidth, displayHeight-65, JAVA2D);
          smooth(4);
          cursor(HAND);
          frameRate(FPS);
    
          //Título da aplicação na Janela do Windows
          frame.setTitle("C.A.L. Anima - Animação - Interação");
    
          //Define fonte para o Texto e seta cor
          fontA     = loadFont("BuxtonSketch-48.vlw");  
          //boldFontA = loadFont("Candara-BoldItalic-48.vlw");
          textFont(fontA, 40);
          fill(#1273C1); 
    
          cp5 = new ControlP5(this);
          criaObjetos(); //Cria Botões ( with Controp5 )
        }
    
        void draw() {
          //if (configurar){
            if (limpaTela) background(255);
    
            textFont(fontA, 40);
            fill(#1273C1);
            text("Selecione uma Opção para Começar...", 10, 30);
            //println("Status execução: " + executando);
          //}
        }
    
        void keyPressed() {
          if (key == ESC ) key = 0;
          //println("Tecla Pressionada... ");
        }
    
        // Util Functions for Hiding/Displaying/Destroy Toggling Sketches:
        //public static final void disableSketch(PApplet p) {
        static final void disableSketch(PApplet p) {
          p.frame.hide();
          p.noLoop();
        }
    
        //public static final void activateSketch(PApplet p) {
        static final void activateSketch(PApplet p) {
          p.frame.show();
          p.loop();
        }
    
        static final void destroySketch(PApplet p) {
          //p.frame.destroy();
          p.destroy();
          //p.frame.exit();
          //p.frame.dispose();
        }
    
        static final void toggleSketch(PApplet p) {
          boolean isActive = p.frame.isVisible();
          p.frame.setVisible(!isActive);
    
          if (isActive)  p.noLoop();
          else           p.loop();
        }
    
        //static final void verificaApplet(PApplet p) {
        boolean verificaApplet(PApplet p) {
          boolean isActive = p.frame.isVisible();
          //p.frame
          println("Estado da Applet : " + isActive);
    
          //if (isActive) setupBalls();
          return (isActive);
        }
    
        void btn01(int theValue) {
          println("Acionado evento btn01 - Index: "+theValue);
          //ExemploA = new exemploA(); 
          try{
            noLoop();
            runSketch(new String[] { "Bolhas" }, ExemploA);
            verificaApplet(ExemploA);
          }finally{
           loop(); 
          }
        }
    
        void btn02(int theValue) {
          println("Acionado evento btn02 - Index: "+theValue);
          //ExemploB = new exemploB();
          runSketch(new String[] { "Paint" }, ExemploB);
        }
    
        void btn03(int theValue) {
          println("Acionado evento btn02 - Index: "+theValue);
          //ExemploC = new exemploC(); 
          //runSketch(new String[] { "Musicas" }, PlaySom);
        }
    
        void criaObjetos(){
          cp5.addButton("btn01")
             .setPosition(50,(height/2)-100)
             .setImages(loadImage("bolhas0.png"), loadImage("bolhas1.png"), loadImage("bolhas2.png"))
             .updateSize();
    
         cp5.addButton("btn02")
            .setPosition(180,(height/2)-100)
            .setImages(loadImage("paint0.png"), loadImage("paint1.png"), loadImage("paint2.png"))
            .updateSize(); 
    
         cp5.addButton("btn03")
            .setPosition(300,(height/2)-100)
            .setImages(loadImage("musica0.png"), loadImage("musica1.png"), loadImage("musica2.png"))
            .updateSize(); 
        }
    
  • /**-------------------------------------------------------------------------------------------------
      *Animation Balls ( In another frame ( Applet ) )
      *-------------------------------------------------------------------------------------------------
    **/
    public static final class exemploA extends PApplet {
      /* OpenProcessing Tweak of *@*<a href="http://www.openprocessing.org/sketch/9793*@*" target="_blank" rel="nofollow">http://www.openprocessing.org/sketch/9793*@*</a>; */
      /* !do not delete the line above, required for linking your tweak if you upload again */
    
      ParticleSystem ps;
      boolean showVectors = false;
    
      void setup(){
        //size(600, 600, P3D);
        size(displayWidth, displayHeight-65, JAVA2D);
        setupBalls();
      }
    
      public void setupBalls(){
        ps = new ParticleSystem(1, new PVector(width/2, height/2,0));
        //smooth();
        println("Executando SetupBalls");
      }
    
      void draw(){
        if (configurar){
          setupBalls();
          configurar = false;
        }
    
        background(255);
    
        PVector G = new PVector(mouseX - width/2,mouseY - height/2);
        //PVector G = new PVector(-Unimotion.getSMSX(),Unimotion.getSMSZ());
        G.normalize();
    
        ps.gravity = G.get();
        ps.run();
        ps.addParticle();
      }
    
      void keyPressed() {
        if (key == ESC ){
          key        = 0;
          configurar = true;
          disableSketch(ExemploA);
          destroySketch(ExemploA);
        }
        showVectors = !showVectors;
      }
    
      class Particle {
        PVector loc;
        PVector vel;
        PVector acc;
    
        color c;
        int radio;
    
        float bounce = 0.8;
        float timer;
        float mass;
        boolean colliding = false;
        PImage img;
        int vez = 0;
    
        Particle(PVector setLoc){
          loc = setLoc.get();
          vel = new PVector(random(-2,2),random(-2,2));
          acc = new PVector(random(-2,2),random(-2,2));
    
          radio = (int)random(3,10);
          mass = radio/2;
    
          c = color(random(0,255),random(0,255),random(0,255));
    
          timer = 255;
    
          img = null;
          vez++;
          println("Iniciando 1 ... " + vez );
        }
    
        Particle(PVector setLoc, PImage setImg){
    
          loc = setLoc.get();
          vel = new PVector(random(-2,2),random(-2,0));
          acc = new PVector(0,0);
    
          radio = (int)random(3,10);
    
          mass = radio/2;
    
          c = color(random(0,255),random(0,255),random(0,255));
    
          timer = 255;
    
          img = setImg;
          //println("Iniciando 2 ...");
        }
    
        void go(){
          update();
          checkBordes();
          render();
        }
    
        void update(){
          vel.add(acc);
          loc.add(vel);
          acc.mult(0);
          timer -= 1.0;
        }
    
        void drawShape(){
          if (img == null) {
            fill(red(c),green(c),blue(c),timer);
            noStroke();
            ellipse(loc.x,loc.y,radio*2,radio*2);
          } else {
            imageMode(CENTER);
            fill(red(c),green(c),blue(c),timer);
            image(img,loc.x,loc.y,radio,radio);
          }
        }
    
        void render(){
          drawShape();
    
          if (showVectors) {
            drawVector(vel,loc,10);
            //drawVector(G,loc,100);
          }
        }
    
        boolean dead(){
          if (timer <= 0.0){
            return true;
          } else {
            return false;
          }  
        }
    
        void checkBordes(){
          if (loc.y + radio >= height){
            loc.y = height - radio;
            vel.y *= -bounce;
          }
    
          if (loc.y - radio <= 0) {
            loc.y = radio;
            vel.y *= -bounce;
          }
    
    
          if(loc.x + radio >= width){
            loc.x = width - radio;
            vel.x *= -bounce;
          }
    
          if (loc.x - radio <= 0){
            loc.x = radio;
            vel.x *= -bounce;
          }
        }
    
        void applyForce(PVector force){
          force.div(mass);
          acc.add(force);
        }
    
        PVector calcGravForce(Particle p){
          PVector dir = PVector.sub(loc,p.loc);
          float d = dir.mag();
          //d = constrain(d,5.0,25.0);
          dir.normalize();
          float force = (9.8 * radio * p.radio) / (d * d);
          dir.mult(force);
          return dir;
        }
    
        void collideEqualMass(Particle p) {
          float d = PVector.dist(loc,p.loc);
          float sumR = radio + p.radio;
          // Are they colliding?
          if (!colliding && d < sumR) {
            // Yes, make new velocities!
            colliding = true;
            // Direction of one object to another
            PVector n = PVector.sub(p.loc,loc);
            n.normalize();
    
            // Difference of velocities so that we think of one object as stationary
            PVector u = PVector.sub(vel,p.vel);
    
            // Separate out components -- one in direction of normal
            PVector un = componentVector(u,n);
            // Other component
            u.sub(un);
            // These are the new velocities plus the velocity of the object we consider as stastionary
            vel = PVector.add(u,p.vel);
            p.vel = PVector.add(un,p.vel);
          } else if (d > sumR) {
            colliding = false;
          }
        }
      }
    
      class ParticleSystem {
        PVector gravity = new PVector(0,9.8);
    
        ArrayList particles;
        PVector origin;
    
        float t = 0;
    
        PImage img = null;
    
        boolean bouncing = false;
    
        ParticleSystem(int num, PVector v){
          particles = new ArrayList();
          origin = v.get();
          for(int i = 0; i < num; i++){
            particles.add(new Particle(origin));
          }
        }
    
        void run(){
          for(int i = particles.size()-1; i >= 0; i--){
            Particle p = (Particle) particles.get(i);
    
            if (bouncing) {
              for(int a = 0; a < particles.size(); a++){
                if(a != i){
                  Particle pa = (Particle) particles.get(a);
                  p.collideEqualMass(pa);
                }
              } 
            }
    
            PVector G = gravity.get();
    
            p.applyForce(G);
            p.go();
    
            if (p.dead()){
              particles.remove(i);
            }
          }
          t += 0.7;
        }
    
        void addParticle(){
          particles.add(new Particle(origin,img));
        }
    
        void addParticle(Particle p){
          particles.add(p);
        }
    
        boolean dead(){
          if (particles.isEmpty()){
            return true;
          } else {
            return false;
          }
        }
      }
    
      void drawVector(PVector v, PVector loc, float scayl) {
        pushMatrix();
        float arrowsize = 4;
        // Translate to location to render vector
        translate(loc.x,loc.y);
        stroke(0);
    
        // Call vector heading function to get direction (note that pointing up is a heading of 0) and rotate
        rotate(v.heading2D());
    
        // Calculate length of vector & scale it to be bigger or smaller if necessary
        float len = v.mag()*scayl;
    
        // Draw three lines to make an arrow (draw pointing up since we've rotate to the proper direction)
        line(0,0,len,0);
        line(len,0,len-arrowsize,+arrowsize/2);
        line(len,0,len-arrowsize,-arrowsize/2);
        popMatrix();
      }
    
      PVector componentVector (PVector vector, PVector directionVector) {
        //--! ARGUMENTS: vector, directionVector (2D vectors)
        //--! RETURNS: the component vector of vector in the direction directionVector
        //-- normalize directionVector
        directionVector.normalize();
        directionVector.mult(vector.dot(directionVector));
        return directionVector;
      }
    }
    
  • /**-------------------------------------------------------------------------------------------------
      * Paint - Key DOWN, Changes shape design ( In another frame (Applet ) 
      *-------------------------------------------------------------------------------------------------
    **/
    public static final class exemploB extends PApplet {
    /** OpenProcessing Tweak of *@*http://www.openprocessing.org/sketch/37327*@* 
        !do not delete the line above, required for linking your tweak if you upload again 
        KEYS:
        SPACEBAR = CLEAR
        RIGHT CLICK = SQUARE
        LEFT CLICK = CIRCLE
        Speed of mouse =  shape size
    
        made by Miranda Kuang
    
        //Other ( Paint )
        OpenProcessing Tweak of *@*http://www.openprocessing.org/sketch/175059*@* 
        !do not delete the line above, required for linking your tweak if you upload again 
    **/
    
      //Variáveis Paint
      float color1 = 255;//color R pintar con pincel
      float color2 = 0;//color G pintar con pincel
      float color3 = 0;//color B pintar con pincel
      int tamany   = 40;//Tamanho Pincel pincel
      boolean corAleat = false;
    
      //---------------------------------------------------------------
      boolean xPressed, aPressed;
      boolean lmouse, rmouse = false;
      float f, k;
    
      //-----------------
      void setup(){
        size(displayWidth, displayHeight-65,JAVA2D);
        background(255);
        smooth();
        noStroke();
        //noCursor();
        cursor(HAND);
      }
    
      //---------------
      void draw(){
        telaPaint();
        if (opcaoDesenho == 1){
          if (mousePressed) desenhaPaint();
        } else if (opcaoDesenho == 2){
          fill(random(75, 225), random(75, 225), random(75, 225));
          brush(mouseX, mouseY, pmouseX, pmouseY);
        }
      }
    
      //-------------
      void mousePressed(){
        if (opcaoDesenho == 1){
          desenhaPaint();
        } else if (opcaoDesenho == 2){  
          if (mouseButton == LEFT){
            lmouse = true;
          }
          if (mouseButton == RIGHT){
            lmouse = false;
          }
        } 
      }
    
      void mouseMoved(){
        if (opcaoDesenho == 1){
          desenhaPaint();
        }
      }
    
      void keyPressed(){
        if (key == ESC ){
          key = 0;
          disableSketch(ExemploB);
          destroySketch(ExemploB);
        }
    
        if (key == ' ') background(255);
    
        if (opcaoDesenho == 1){ //Paint 
          //Aumentar y disminuir de tama�±o al apretar + y -
          if (key == '+' && tamany < 50) {
            tamany = tamany + 1;
          }
    
          if (key == '-' && tamany > 0) {
            tamany = tamany - 1;
          }
    
          //Color del pincel aleatorio   
          if (key == 'R' || key == 'r') {
            corAleat = !corAleat;
          }
    
          if (key == CODED){
            if (keyCode == LEFT) lmouse = true;
            else if (keyCode == RIGHT) lmouse = false;
          }
        }
    
        if (key == CODED){
          if (keyCode == DOWN ) mudaTipoAnimacao();
          if (keyCode == UP ) mousePressed();
        } 
      }
    
      void mudaTipoAnimacao(){
        background(255);
        if (opcaoDesenho == 1){
          //colorMode(RGB);
          /*f = random(0, 255);
          k = 255;
          colorMode(HSB, 255);
          color c = color(random(75,255), random(75,255), random(75,255));
          fill(c);
          float value = brightness(c);
          fill(value);*/
          opcaoDesenho = 2;
        } else if(opcaoDesenho == 2){
          //colorMode(HSB, 255);
          corAleat     = false;
          opcaoDesenho = 1;
        }
      }
    
      //-------------
      void brush(int x, int y, int px, int py){
        float speed = abs(x-px) + abs(y-py);
        //--------------
        if (lmouse){
          rect(x, y, speed/2, speed/2);
        } else 
          ellipse(x, y, speed/2, speed/2);
      }
    
      void telaPaint(){
        strokeWeight(1);
        stroke(0);
    
        //BORDES TABLA DIBUJO
        fill(90, 150, 200, 80);
        rect(0,0,150,displayHeight-68);
    
        //rect(0,0,1000,20);
        //rect(0,0,141,695);
        //rect(0,675,1000,20);
        //rect(980,0,20,695);
    
        //Rectangulo borde colores
        rect (22,55,95,235);
        fill(0);
    
        //texto colores
        textSize(23);
        text("Cores",23,45);
    
        //CUADORADOS COLORES
        //Fila 1
        fill (163, 73, 164);
        rect (33,63,20,20);
        fill (200, 191, 231);
        rect (60,63,20,20); 
        fill (63, 72, 204);
        rect (87,63,20,20);
    
        //Fila 2    
        fill (112, 146, 190);
        rect (33,90,20,20);
        fill (0, 162, 232);
        rect (60,90,20,20); 
        fill (153, 217, 234);
        rect (87,90,20,20);
    
        //Fila 3    
        fill (34, 177, 76);
        rect (33,117,20,20);
        fill (181, 230, 29);
        rect (60,117,20,20); 
        fill (255, 242, 0);
        rect (87,117,20,20);
    
        //Fila 4    
        fill (239, 228, 176);
        rect (33,144,20,20);
        fill (255, 127, 39);
        rect (60,144,20,20); 
        fill (255, 201, 14);
        rect (87,144,20,20);
    
        //Fila 5    
        fill (237, 28, 36);
        rect (33,171,20,20);
        fill (255, 174, 201);
        rect (60,171,20,20); 
        fill (136, 0, 21);
        rect (87,171,20,20);
    
        //Fila 6    
        fill (185, 122, 87);
        rect (33,198,20,20);
        fill (127, 127, 127);
        rect (60,198,20,20); 
        fill (195, 195, 195);
        rect (87,198,20,20);
    
        //Fila 7    
        fill (0, 0, 0);
        rect (33,225,20,20);
        fill (255, 255, 255);
        rect (60,225,20,20); 
        fill (255, 255, 255);
        rect (87,225,20,20);
    
        //Cuadro color actual
        fill(color1,color2,color3);
        rect(33,252,74,20);
    
        //texto ?
        fill(0);
        textSize(20);
        text("?",93,243); 
    
        //texto RGB
    
        //textSize(20);
        //text("Code RGB",18,352); 
        //textSize(10);
        //text("R: "+color1,18,380);
        //text("G: "+color2,18,400);
        //text("B: "+color3,18,420);
    
        //CLEAR
        fill(#81B9F5);
        //ellipse(70,520,80,80);
        rect(20, 500, 110, 50);
        fill(0);
        textSize(22);
        text("Limpar", 40, 532); 
    
        fill(#81B9F5);
        rect(20,560,50,40);
        fill(0);
        textSize(30);
        text("+", 33, 590);
    
        fill(#81B9F5);
        rect(80,560,50,40);
        fill(0);
        textSize(30);
        text("-", 95, 590); 
    
        //PRESS R
        textSize(15); 
        text("Pressione 'r' para",13,640); 
        text("cor Aleatória",13,660); 
    
        //Pintar al apretar
        if ( mousePressed){
          strokeWeight (tamany);
          stroke (color1, color2, color3);
          line (mouseX,mouseY,pmouseX,pmouseY);
        }
    
        if (corAleat) {
          corAuto();
        }
      }
    
      void desenhaPaint(){
        //Limpiar pantalla al seleccionar la cruz
        if (mousePressed && mouseX >35 && mouseX <105 && mouseY >491 && mouseY<550){
          background(255,255,255);
        } 
    
        //Aumentar espessura de traçado
        if (mouseX > 22 && mouseX < 70 && mouseY > 561 && mouseY < 597){
          tamany = tamany + 1;
        } 
    
        //Diminuir espessura de traçado
        if (mouseX > 82 && mouseX < 128 && mouseY > 561 && mouseY < 597){
          tamany = tamany - 1;
        } 
    
        // Cambiar de color al seleccionar el cuadrado de color
        //FILA 1
        if (mouseX>33 && mouseX<53 && mouseY>63 &&mouseY< 83) {
         color1 = 163;
         color2 = 73;
         color3 = 164;
        }
    
        if (mouseX>60 && mouseX<80 && mouseY>63 &&mouseY<83 ) {
          color1 = 200;
          color2 = 191;
          color3 = 231;
        }
    
        if (mouseX>87 && mouseX<107 && mouseY>63 &&mouseY<83 ) {
          color1 = 63;
          color2 = 72;
          color3 = 204;
        }
    
        //FILA 2
        if (mouseX>33 && mouseX<53 && mouseY>90 &&mouseY<110 ) {
          color1 = 112;
          color2 = 146;
          color3 = 190;
        }
    
        if (mouseX>60 && mouseX<80 && mouseY>90 &&mouseY<110 ) {
          color1 = 0;
          color2 = 162;
          color3 = 232;
        }
    
        if (mouseX>87 && mouseX<107 && mouseY>90 &&mouseY<110 ) {
          color1 = 153;
          color2 = 217;
          color3 = 324;
        }
    
        //FILA 3
        if (mouseX>33 && mouseX<53 && mouseY>117 &&mouseY<137 ) {
          color1 = 34;
          color2 = 177;
          color3 = 76;
        }
    
        if (mouseX>60 && mouseX<80 && mouseY>117 &&mouseY<137 ) {
          color1 = 181;
          color2 = 230;
          color3 = 29;
        }
    
        if (mouseX>87 && mouseX<107 && mouseY>117 &&mouseY<137 ) {
          color1 = 255;
          color2 = 242;
          color3 = 0;
        }
    
        //FILA 4
        if (mouseX>33 && mouseX<53 && mouseY>144 &&mouseY<164 ) {
          color1 = 239; 
          color2 = 228;
          color3 = 176;
        }
    
        if (mouseX>60 && mouseX<80 && mouseY>144 &&mouseY<164 ) {
          color1 = 255;
          color2 = 127;
          color3 = 39;
        }
    
        if (mouseX>87 && mouseX<107 && mouseY>144 &&mouseY<164 ) {
          color1 = 255;
          color2 = 201;
          color3 = 14;
        }
    
        //FILA 5
        if (mouseX>33 && mouseX<53 && mouseY>171 &&mouseY<191 ) {
          color1 = 237;
          color2 = 28;
          color3 = 36;
        }
    
        if (mouseX>60 && mouseX<80 && mouseY>171 &&mouseY<191 ) {
          color1 = 255;
          color2 = 174;
          color3 = 201;
        }
    
        if (mouseX>87 && mouseX<107 && mouseY>171 &&mouseY<191 ) {
          color1 = 136;
          color2 = 0;
          color3 = 21;
        }
    
        //FILA 6
        if (mouseX>33 && mouseX<53 && mouseY>198 &&mouseY<218 ) {
          color1 = 185;
          color2 = 122;
          color3 = 87;
        }
    
        if (mouseX>60 && mouseX<80 && mouseY>198 &&mouseY<218 ) {
          color1 = 127;
          color2 = 127;
          color3 = 127;
        }
    
        if (mouseX>87 && mouseX<107 && mouseY>198 &&mouseY<218 ) {
          color1 = 195;
          color2 = 195;
          color3 = 195;
        }
    
        //FILA 7
        if (mouseX>33 && mouseX<53 && mouseY>225 &&mouseY<245 ) {
          color1 = 0;
          color2 = 0;
          color3 = 0;
        }
    
        if (mouseX>60 && mouseX<80 && mouseY>225 &&mouseY<245 ) {
          color1 = 255;
          color2 = 255;
          color3 = 255;
        }
    
        if (mouseX>87 && mouseX<107 && mouseY>225 &&mouseY<245 ) {
          color1 = random(255);
          color2 = random(255);
          color3 = random(255);
        }
      }
    
      void corAuto(){
        color1 = random(255);
        color2 = random(255);
        color3 = random(255);  
      }
    }
    
  • Hello again,

    Sorry, this simple mistake of the arrows effect, happened after I put the ESC key to close the screen because using X, closes the entire application ...

    Sorry again ...

    I still can not solve the problem, the running the setup () again, after the start of aa first time the application if they can suggest something, it would be of great help.

    Thank you.

  • Oh yes the code which was causing the effect ...

    void keyPressed() { if (key == ESC ){ key = 0; configurar = true; disableSketch(ExemploA); //destroySketch(ExemploA); } -->//showVectors = !showVectors; }

  • edited August 2015

    what do you need to be solved?

    what is the problem?

  • I don't have time to look into it

    you could post the code here https://gist.github.com/

    or provide an mcve - http://stackoverflow.com/help/mcve - but your problem is probably not reducable to an mcve

  • Hello Chrisir,

    The problem still seems to have some "side effects", when you enter a second time on the screen ... as screen background with other color, for example ...

    I figured it would restart some variables that are normally initiated in setup (), so the call again.

    But got a way around this, although it still has some unexpected effect.

    I still can not solve another problem ... which is when closing a second window with (x), closes the entire application.

    I tried to control it with the ESC key, but time works, and time does not.

    void keyPressed() {
        if (key == ESC ){
          key        = 0;
          executando = false;
          disableSketch(ExemploA);
          destroySketch(ExemploA);
          setupBalls();
        }
    
        if (key == 'V' || key == 'v')
          showVectors = !showVectors;
      }
    

    Any idea how to fix this? That is, how close the window with (X), and not close any application?

    Thanks again for your attention.

  • One more detail,

    The ESC also (like when you close with X) closes the application in any window that is open, without this control that tried to put (key = 0) when you press the key.

    This is a drawback, because need return to the Menu screen, so I am a means of controlling it.

    Thanks,

  • ask gotoloop ...

  • Hello Chrisir, Gotoloop ...

    I think it would be really interesting to find a solution to this problem, I think this is a very good way to work with multiple sketches, so each gets their separate controls, facilitating the development.

    The other way as you explained, also works well, the problem is that sometimes arise some "side effects", which is more difficult to control, as it adds programs to the Project.

    As I mentioned before, this project aims to beneficar people with mobility difficulties, so some features "ordinary" as the "Paint" and "MediaPlayer" ... because an application in Processing for example, we can add other features beyond Keyboard and Mouse, as the Kinect, Leap Motion (and others with the Arduino) ... anyway, thus ways for people with a disability, can do some type of interaction with a computer.

    I am grateful for the help I have received so far without your help, it would be very difficult to move forward ...

    What about you Gotoloop, any suggestions on how to solve it?

    In other words, noting that the problem is that when closing the window (at X) and is the second open window closes entire project.

    If I put the control in time key works not time (sometimes need to press the mouse ja window to function, sometimes closes all to no (X) ...

    There would be some way to define a sketch as "Main", where the menu, is when closing a second open window, close it alone, and return to the Menu?

    Thanks again for your attention.

  • Sorry but I also wish I knew how to control window buttons' behavior!
    Perhaps if we could hide window's buttons but dunno how either!
    I've got a vague idea of some forum thread about button hiding, but am not so sure!
    In short, that's Java's advanced JFrame stuff. It's beyond me! X_X

  • Hello GoToLoop,

    Thanks for the feedback, do not apologize for that, I do I have to apologize for being "disturbing" so so ... but I believe that solving it will help me a lot in the project I'm developing, and believe it can be used by others , which are likely to go through the same problem ...

    I'll keep trying a means to better get around this, and having something new, I put here ...

    Thank you very much for now again ...

Sign In or Register to comment.