I’m trying to use a loop to create 10 objects at a time then use another loop in Draw() method to call the objects’ render() methods.
At first I tried creating and calling objects method manually and it worked. Now I want to do that with loops, I’m not sure why the program shows error.
void setup() {
size(600, 320);
}
int[] avVal = {-1, 1};
class Obj { //<---------my object class
int x;
int y;
void render() {
int ran1 = int(random(2));
int ran2 = int(random(2));
int vx = int(random(2));
int vy = int(random(2));
this.x += vx*avVal[ran1];
this.y += vy*avVal[ran2];
point(this.x, this.y);
}
}
Obj[] arr = new Obj[10]; //<---------create an array to contain 10 objects
for (int i = 0; i < 10; i++) { //<---------loop to add 10 objects to array
Obj ob = new Obj();
ob.x = int(random(600)); //<---------set random starting coordinates for objects
ob.y = int(random(320)); //<--------/
arr[i] = ob;
}
**_get error underlined here: Error on "VariableDeclarators"_**
\/ \/
void draw() {
for (int u = 0; u < 10; u++) { //<---------this loop to iterate through the array
arr[u].render(); //<---------call each object in array to draw
}
}
your for loop it is outside of any methods.
assuming your arr variable it is global and you want create 10 objects in the setup function you can arrange your code as this :
Obj[] arr = new Obj[10];
int[] avVal = {-1, 1};
void setup()
{
size(600, 320);
for (int i = 0; i < 10; i++)
{
Obj ob = new Obj();
ob.x = int(random(600));
ob.y = int(random(320));
arr[i] = ob;
}
}
void draw()
{
for (int u = 0; u < 10; u++)
{
arr[u].render();
}
}
class Obj
{
int x;
int y;
void render()
{
int ran1 = int(random(2));
int ran2 = int(random(2));
int vx = int(random(2));
int vy = int(random(2));
this.x += vx*avVal[ran1];
this.y += vy*avVal[ran2];
point(this.x, this.y);
}
}