Can I make words float around the screen with the word I type in?

I was trying to make a code that can make the word of sentence I type in would float around the screen.

when I type the letters and hit enter, the typed sentence will bounce around.

It was kinda tricky… since I didnt code enough with string, key etc.

this code does change the letter but its just one letter, and I dont know how to put new strings in it.

should I use array or vector??

float posx, posy;
float addx, addy;
String s;
void setup(){
  size(1200, 720);
  background(176);
  smooth();
  addx = random(-5, 5);
  addy = random(-5, 5);
  posx = width/2;
  posy = height/2;
}

void draw(){
  background(176);

  textSize(32);
  textWidth(key);
  text(key, posx, posy);

  posx += addx;
  posy += addy;

  if(posx < 0 || posx > width - textWidth(key)){
    addx *= -1;
  }
  if(posy < 16 || posy > height){
    addy *= -1;
  }
  

}

If you are making this interactive, that means you will not know how long the text will be. So, you want to start with an empty array, and store all the keypresses in another variable, then, when the user hits enter, push the collected string into the array you created earlier.

But you are not only tracking the text but also position, speed, etc. Therefore, it will be better to create an object each time the user hits enter, and store all the data in the object (text, x, y, speed, etc.) you can create this object using class.

Then, you iterate over each object using a for loop.

1 Like

here is an example with 2 screens:

one screen where you enter the sentence
one where the sentence move



float posx, posy;
float addx, addy;
String s="";

boolean wordHasBeenEntered=false; 

void setup() {
  size(1200, 720);
  background(176);
  smooth();
  addx = random(-5, 5);
  addy = random(-5, 5);
  posx = width/2;
  posy = height/2;
}

void draw() {
  background(176);

  if (wordHasBeenEntered) {

    textSize(32);
    textWidth(key);
    text(s, posx, posy);

    posx += addx;
    posy += addy;

    if (posx < 0 || posx > width - textWidth(key)) {
      addx *= -1;
    }
    if (posy < 16 || posy > height) {
      addy *= -1;
    }
  }

  //-----------------------------------

  else {
    //
    text("Please enter your word:  \n"
      +s, posx, posy);
  }//else 
  //
}

void keyPressed() {
  if (wordHasBeenEntered) 
    return; //leave 
  if (key==CODED)
    return; //leave  
  if (key == ENTER||key==RETURN) {
    wordHasBeenEntered=true;
    return;
  }
  s+=key;
}
//

When you want to split the sentences to words, use split() command to make that array arr1. In keyPressed, section RETURN

declare arrays of the length of arr1 named x,y,addx,addy

fill them with random values

apply them in a for-loop in draw() in section if (wordHasBeenEntered) {

2 Likes

wow this really helped!! thank you very much!!!

1 Like