Hi all! I’m trying to convert Daniel Shiffman’s sine wave example to a class so I can have multiple instances of it.
However, when I start creating the class:
class Wave {
constructor(){
this.xspacing = 20;
this.w = w;
this.theta = 0.0;
this.amplitude = 25.0;
this.period = 500.0;
this.dx = dx
this.yvalues = yvalues;
}
calcWave(){
this.theta += 0.2;
var x = this.theta
for (let i = 0; i < this.yvalues.length; i++){
this.yvalues[i] = sin(x) * this.amplitude;
x += this.dx;
}
}
renderWave(){
noStroke();
fill(0, 47, 75, 127);
for (let x = 0; x < this.yvalues.length; x++){
ellipse(x*this.xspacing, height/2+this.yvalues[x], 66, 16)
}
}
}
let wave = new Wave();
const numWaves = 10
let waves = Array(numWaves)
I run into the problem where the variables w, dx, and yvalues, are not initially assigned to a value of some sort. Could I get some direction in how to handle this? I don’t think you would put just those in the constructor because you’re not assigning them to the instance (let wave = new Wave()).
My errors, naturally, result in ‘w is not defined’.
Here I can see two things: yvalues is an array and it has elements so for size to return non-zero ( or even better, it will not return not defined). The only way for this to work is to use one of the definitions for Array(): Array - JavaScript | MDN
Consider:
yvalues=new Array(arrayLength);
Based on the link you provided, the value of arrayLength should be width/16. You have either of two options: In the constructor you initialized your array based on this constant value or you provide this value as a parameter of your constructor like this:
constructor(w){
this.w = w
.... OTHER lines of code
}
let wave = new Wave(width/16);
Which one should you implement? One is preferred over the other, only because you can adjust the size on creation. For demonstration purposes, either would work.
I‘m not sure why noone said this, But your class doesn‘t have any class intern variables that it could set with this.w. You Need to add them (preferably) just before the constructor. Something like :
class Wave {
w = 0;
xSpace = 0;
Wave(int w_, int xSpace_) {
this.w = w_;
this.xSpace = xSpace_;
}
}
Note, since noone said this before, i‘m not all too sure…
Thank you everyone, really appreciate the direction!
It leads me to another question, then, of the Jitter example that uses a class (albeit, declared with function). My confusion stems from the fact that there is no assignment of those parameters to a constructor so how is this example different to my first attempt at not declaring anything in the constructor?