Child parts not moving with parent objects
in
Programming Questions
•
1 year ago
The sketch has two Main objects.
Each Main has two Part child objects.
But when the Main objects move, the Parts are not staying with them.
How does that work?
- // MainAndParts
- Main m1, m2;
- int x = 100;
- int y = 100;
- int w = 90;
- int h = 90;
- int xx = x;
- int a;
-
- void setup() {
- size(300,300);
- smooth();
- m1 = new Main(x, y, w, h, color(100));
- m2 = new Main(x, y+h+20, w, h, color(180));
- }
-
- void draw() {
- background(255);
- m1.display();
- m2.display();
- text("click to move Main", 12, height-12);
- }
-
- void mousePressed() {
- m1.move();
- m2.move();
- }
- class Main {
- int x;
- int y;
- int w;
- int h;
- color c;
- Part p1;
- Part p2;
- Main(int x_, int y_, int w_, int h_, color c_) {
- x = x_;
- y = y_;
- w = w_;
- h = h_;
- c = c_;
- p1 = new Part(x, this.y, 20, 20, color(250), 1);
- p2 = new Part(x, this.y + 30, 20, 20, color(250), 2);
- }
- void display() {
- fill(c);
- stroke(0);
- ellipse(xx,y,w,h);
- p1.display();
- p2.display();
- }
-
- void move() {
- xx += 2;
- }
- }
-
- class Part {
- int x;
- int y;
- int w;
- int h;
- color c;
- int id;
- Part(int x_, int y_, int w_, int h_, color c_, int id_) {
- x = x_;
- y = y_;
- w = w_;
- h = h_;
- c = c_;
- id = id_;
- }
-
- void display() {
- fill(c);
- stroke(0);
- ellipse(x, y, w, h);
- fill(0);
- text(str(id), x-4, y+4);
- }
- }
1