I'm trying to figure out how to create an object on-the-fly, meaning while a program is running, after setup() has already run. In the sample code below, I'm trying to create a new "mrect" object whenever the mouse is clicked. So, the program starts out with an mrect.length of only 1, but hopefully, upon each mouse click, that number is incremented.
I've used arrays of objects before, but it seems that creating a new object is not really as simple as appending a new value to the array. Should it be?
Copy and paste the following into a new sketch and it will run. Then try uncommenting the two lines I have commented out in mousePressed(), one at a time. Those are the two methods I have tried to append/expand the array. What am I doing wrong? What is the syntax for adding a new object to an object array and initializing it at the same time?
Thanks!
Code:MRect[] mrect = new MRect[1];
void setup()
{
size(500, 500);
fill(255, 150);
noStroke();
mrect[0] = new MRect(1, 50, 0.25, 0.01*height); //Initialize the first mrect
}
void draw()
{
background(0);
for (int i = 0; i < mrect.length; i++) { //Loops through all mrect objects
mrect[i].display();
}
for (int i = 0; i < mrect.length; i++) { //Loops through all mrect objects
mrect[i].move(mouseX, mouseY, 30);
}
}
void mousePressed() {
MRect[] mrectNew = new MRect[1];
mrectNew[0] = new MRect(5, 200, 50, 0.2*height);
//mrect = append(mrect, mrectNew); //Triggers "ype of the right sub-expression, "java.lang.Object", is not assignable to the variable" error
//MRect[] mrect = (MRect[]) expand(mrect); //Triggers "var may be accessed before having been definitely assigned a value" error
println(mrect.length);
}
class MRect
{
int w; // single bar width
float xpos; // rect xposition
float h; // rect height
float ypos ; // rect yposition
float d; // single bar distance
MRect(int iw, float ixp, float ih, float iyp) {
w = iw;
xpos = ixp;
h = ih;
ypos = iyp;
println("created new object");
}
void move (float posX, float posY, float damping) {
float dif = ypos - posY;
if (abs(dif) > 1) {
ypos -= dif/damping;
}
dif = xpos - posX;
if (abs(dif) > 1) {
xpos -= dif/damping;
}
}
void display() {
rect(xpos + (w*10), ypos, w, height*h);
}
}