Here is a possible way:
Code:TargetObj[] myTargets;
LinkObj myLinker;
void setup() {
myTargets = new TargetObj[2];
myTargets[0] = new TargetObj(25, 10);
myTargets[1] = new TargetObj(75, 90);
int[] dx = { 1, -1 }, dy = { 1, -1 };
myLinker = new LinkObj(myTargets, dx, dy);
}
void draw() {
myLinker.update();
for (int i = 0; i < myTargets.length; i++)
{
myTargets[i].display();
}
}
class TargetObj {
float x,y;
TargetObj(float tx, float ty) {
x = tx;
y = ty;
}
void display() {
ellipse(x, y, 2, 2);
}
}
class LinkObj {
TargetObj[] linkedTargets;
int[] dirX, dirY;
LinkObj(TargetObj[] lt, int[] dx, int[] dy) {
linkedTargets = lt;
dirX = dx; dirY = dy;
}
void update() {
for (int i = 0; i < linkedTargets.length; i++)
{
linkedTargets[i].x += dirX[i];
linkedTargets[i].y += dirY[i];
}
}
}
Here is a slightly more convoluted variant:
Code:TargetObj[] myTargets;
LinkObj myLinker;
void setup() {
myTargets = new TargetObj[2];
myTargets[0] = new TargetObj(25, 10, 1, 1);
myTargets[1] = new TargetObj(75, 90, -1, -1);
myLinker = new LinkObj();
for (int i = 0; i < myTargets.length; i++)
{
myLinker.addTarget(myTargets[i]);
}
}
void draw() {
myLinker.update();
}
class TargetObj {
float x, y;
float dx, dy;
TargetObj(float tx, float ty, float mx, float my) {
x = tx; y = ty;
dx = mx; dy = my;
}
void display() {
ellipse(x, y, 2, 2);
}
void update() {
x += dx;
y += dy;
}
}
class LinkObj {
ArrayList linkedTargets;
LinkObj() {
linkedTargets = new ArrayList();
}
void addTarget(TargetObj linkedTarget) {
linkedTargets.add(linkedTarget);
}
void update() {
for (int i = 0; i < linkedTargets.size(); i++)
{
TargetObj to = (TargetObj) linkedTargets.get(i);
to.update();
to.display();
}
}
}
I found logical to put the direction of move in the target object, you can add a method to update the direction too. But if you prefer the linker to control directions, you can add another array list, etc. Likewise, you can separate target move and display, etc.