How to optmize my code?
in
Programming Questions
•
5 months ago
Hey all!
I'm working on a program that draws a wave using several line() functions, but I think maybe there is a more efficient way to do so. I need to use the line functions because I'm putting some noise in the wave too. Well, I think it's better if you run the code, so here it is:
Is there any obvious way to optimize the code so that it can run better?
I'm working on a program that draws a wave using several line() functions, but I think maybe there is a more efficient way to do so. I need to use the line functions because I'm putting some noise in the wave too. Well, I think it's better if you run the code, so here it is:
- int val=50;
- Wave onda;
- void setup(){
- size(600,300);
- background(255);
- strokeWeight(2);
- smooth();
- frameRate(60);
- PVector offset;
- offset = new PVector(0,height/2);
- // Para onda ficar suave é necessário que a frequência seja uma razão da largura do sketch
- onda = new Wave(offset, height/3, width/100, 0.0);
- }
- void draw(){
- //background(244,30);
- onda.display();
- noStroke();
- fill(255,30);
- rect(0,0,width,height);
- stroke(2);
- print(val+"\n");
- }
- void keyPressed(){
- switch(keyCode){
- case UP:
- val-=5;
- break;
- case DOWN:
- val+=5;
- break;
- }
- }
- class Wave {
- PVector offset, p, last;
- float amplitude;
- float frequency;
- float angle;
- //constructor
- Wave(PVector off, float amp, float fre, float ang) {
- offset = new PVector(off.x, off.y);
- amplitude = amp;
- frequency = fre;
- angle = ang;
- last = new PVector(offset.x, offset.y);
- }
- void display() {
- p = new PVector(0,0);
- for (float x=0; x<=width; x+=1){
- p.x = offset.x + x;
- p.y = offset.y + (amplitude * sin(radians(angle)));
- p.y += customRandom(val);
- //p.y += 30 * cos(rand);
- //print(customRandom()+"\n");
- line(last.x, last.y, p.x, p.y);
- last.x = p.x;
- last.y = p.y;
- angle+=frequency/2;
- if(angle>360-frequency/2)
- angle=0;
- }
- last.x=offset.x;
- }
- float customRandom(int amp){
- float rand = random(50);
- float ret = sin(noise(rand))*amp;
- return ret;
- }
- }
Is there any obvious way to optimize the code so that it can run better?
1