Text following a sine wave pattern

Hi. Trying to get some help with this code. Pretty much want to have each letter in the string be a part of a sine wave. Any idea how to do this? My code seems to be stacking each letter on top of each other. Might be the way I have my for loops setup, but I’m not sure.

Thanks in advance!

int xspacing = 16;   // How far apart should each horizontal location be spaced
int w;              // Width of entire wave

float theta = 0.0;  // Start angle at 0
float amplitude = 75.0;  // Height of wave
float period = 500.0;  // How many pixels before the wave repeats
float dx;  // Value for incrementing X, a function of period and xspacing
float[] yvalues;  // Using an array to store height values for the wave
PFont f;

String message="THE UNKNOWN";


void setup() {
  size(640, 360);
  f=createFont("Helvetica", xspacing, true);
  textFont(f);
  w = width+16;
  dx = (TWO_PI / period) * xspacing;
  yvalues = new float[w/xspacing];
}

void draw() {
  background(0);
  calcWave(.02);
  renderWave();
}

void calcWave(float v) {
  // Increment theta (try different values for 'angular velocity' here
  theta += v;

  // For every x value, calculate a y value with sine function
  float x = theta;
  for (int i = 0; i < yvalues.length; i++) {
    yvalues[i] = sin(x)*amplitude;
    x+=dx;
  }
}

void renderWave() {
  noStroke();
  fill(255);
  
  for (int x = 0; x < yvalues.length; x++) {
    for (int i =0; i<message.length(); i++) {
   

      char currentChar=message.charAt(i);
      text(currentChar, x*xspacing,  height/2+yvalues[x]);
    }
  }
}

Hello,

Try this in one loop:

char currentChar = message.charAt(x%11);

image

:)

1 Like

HI. This totally works. Do you mind telling me why this works so I know for future? Also my code is looking pixilated now. Can you send me your code to produce this result so I can compare?

Hello,

% is the modulo operator.
Look it up in the references:

There are lots of resources on this operator out there.

Write some sample code to understand it.

Example:

void setup() 
	{
  size(100, 100);
  
  for (int x = 0; x < 100; x++) 
    {
    int y = x%20;  
    println(x, y);  
    point(x, y);    
    }
  }

image

:)