javarandomarraylistprocessingmouseevent

ArrayList for random strings with mousePressed in Processing (also rotation)


I am new to coding and Processing (so bear with me). I have a class project I need to finish and I need help with one component in my code. I have a mousePressed function within my code that allows for random strings of text to appear in a rotating fashion. However, I want the text to rotate even after the mouse has been released at any RANDOM spot where the viewer released the mouse. I want the viewer to be able to do this (basically an infinite amount of times), but all of the text will rotate simultaneously, not just one string of text at a time. I know I need some ArrayList function to start with, but I don't know where to start since I have many moving pieces in my code.

I hope this makes sense :) but any feedback/EXAMPLES will be VERY much appreciated!

Thank you!

    String [] sentences= {
          "Hello",
          "Good morning",
          "Good night",
    };
    float theta;
    int index = 0;
    
    void setup() {
          background (0);
          size(700, 700);
          textSize(20);
    }

    void draw() {
          background(0);
          pushMatrix();
          fill(255);
          textAlign(CENTER);
          translate(mouseX, mouseY);
          rotate(theta);
          text(sentences[index], 0, 0);
          popMatrix();
        
          theta += 0.02;
    }

    void mousePressed () {
          index = int(random(3));
    }

I've already tried to use an ArrayList with PVector, but the code didn't seem to recognize some of the variables I used. So an example of an ArrayList I could use would be very helpful :)


Solution

  • Check this code.

    // Import the ArrayList class
    import java.util.ArrayList;
    
    ArrayList<PVector> textPositions = new ArrayList<PVector>();
    ArrayList<String> textStrings = new ArrayList<String>();
    
    void setup() {
      size(700, 700);
      textSize(20);
    }
    
    void draw() {
      background(0);
    
      // Iterate through all stored text positions and strings
      for (int i = 0; i < textPositions.size(); i++) {
        PVector pos = textPositions.get(i);
        String textString = textStrings.get(i);
    
        pushMatrix();
        fill(255);
        textAlign(CENTER);
        translate(pos.x, pos.y);
        rotate(theta);
        text(textString, 0, 0);
        popMatrix();
      }
    
      theta += 0.02;
    }
    
    void mousePressed () {
      // Add the current mouse position and a random string to the ArrayLists
      PVector mousePos = new PVector(mouseX, mouseY);
      textPositions.add(mousePos);
      textStrings.add(sentences[int(random(3))]);
    }
    

    You need to import this code initially.

    import processing.core.PVector;