mrklever
YaBB Newbies
Offline
Posts: 2
How to create and fill an array with classes
Jan 22nd , 2010, 10:53am
Is there a good way to spawn multiple instances of a custom class without typing it out? i.e. CustomClass instace1 = new CustomClass(); This method works but is inefficient when I need to create 100+ instances of the custom class. I was thinking that a for loop would work well for this, but I don't know how to use a for loop to create multiple instances. Here is my code: import processing.opengl.*; int spacer = 8; int sizer = 40; ColorSquare square001 = new ColorSquare(0,spacer,random(0,(width-sizer))); ColorSquare square002 = new ColorSquare(0,spacer,random(0,(width-sizer))); ColorSquare square003 = new ColorSquare(0,spacer,random(0,(width-sizer))); //all the way up to ColorSquare square126 = new ColorSquare(2,(spacer*7+sizer*6),random(0,width-sizer)); void setup(){ size(700,352, OPENGL); smooth(); noStroke(); frameRate(40); colorMode(RGB, 255, 255, 255, 100); } void draw(){ background(0); square001.updater(); square002.updater(); square003.updater(); //all the way up to square126.updater(); } //ColorSquare(color, v row, starting h place) class ColorSquare { int locY, fillColor; float locX, xVelo, xAccel, mass, mouseMass, massDist, grav, xGrav; ColorSquare(int a,int b, float c) { fillColor = a; locY = b; locX = c; xVelo = 0; xAccel = 0; mass = (random(2,6) * 100); mouseMass = (random(5,10) * 1000); massDist = 0; grav = 0; xGrav = 0; } void updater(){ massDist = dist(mouseX, mouseY, locX, locY); if(massDist<40){massDist = 40;} grav = mass * mouseMass / pow(massDist,2)* 5; xGrav = grav * ((mouseX - locX)/massDist); xAccel = xGrav / mass; xVelo = xVelo + xAccel; locX = locX + xVelo; if(locX>=(width-sizer)){locX = (width-sizer);} else if(locX<=0) {locX = 0;} switch(fillColor) { case 0: fill(255,0,0,30); break; case 1: fill(0,255,0,30); break; case 2: fill(0,0,255,30); break; } rect(locX, locY, sizer, sizer); } }