Search code examples
colorsprocessingorbit

How to change the color of each ellipse in an array in Processing?


I'm trying to figure out how to change the colors of the three ellipses gravitating around the center ellipse. At the moment they are all red, but I would like to have one be green, one be red, one be yellow for example. Can anyone think of a way to do that?

This is my Processing code:

class OrbitalBody {

float ox, oy, x, y, m, a;

OrbitalBody(float originX, float originY, float startX, float startY, float mass, float speed) {
        ox = originX;
        oy = originY;
        x = startX;
        y = startY;
        m = mass;
        a = speed / 200;
}

void update() {
// creates the orbit;

float nx = (x-ox) * cos(a) - (y-oy) * sin(a),
      ny = (x-ox) * sin(a) + (y-oy) * cos(a);
      x = nx+ox;
          y = ny+oy;
}

void draw() {
// defines the color of the ellipses, now:red;
fill(255,0,0);
ellipse(x,y,m,m);
}
}

ArrayList<OrbitalBody> bodies = new ArrayList<OrbitalBody>();
int mx, my;


void setup() {
size(420, 420);
mx = width/2;
my = height/2;


// distances([3]bodies-(mx,my) is equal. Meaning all three bodies rotate on the same orbit, value now: mx-100;

fill(0,255,0);
bodies.add(new OrbitalBody(mx, my, mx-100, my, 10, 10));
fill(0);
bodies.add(new OrbitalBody(mx, my, mx-100, my, 20, 3));
bodies.add(new OrbitalBody(mx, my, mx-100, my, 5, 13));

ellipseMode(CENTER);
}

void draw() {

// defines background color, now:white;
background(255);
noStroke();

// defines center cercle color value, now:pink;
// second value:alpha channel;
fill(#ec5b94,80); 

// mx and my are the coordinates of the center pink cercle;
ellipse(mx,my,50,50);
for(OrbitalBody b: bodies) {
          b.update();
          b.draw();
}
}

Solution

  • Perhaps you could instantiate each OrbitalBody with a color parameter and then use that parameter in OrbitalBody's draw method.

    Basically, the class would look something like:

    class OrbitalBody {
    
        float ox, oy, x, y, m, a;
        color c;
    
        OrbitalBody(float originX, float originY, float startX, float startY, float mass, float speed, color bodyColor) {
            // Do stuff
            c = bodyColor;
        }
    
        void draw() {
            fill(c);
            ellipse(x,y,m,m);
        }
    }