Array syntax in this code does not hold y variable

Referring to Dan Shiffman book Learning Processing Ch 9 Arrays ~ex 9-12~ p.182-3

The y variable – random(height) – in the “Zoogies” constructor in setup does not maintain the random y variable assigned. (in contrast, the randomly assigned x variable IS maintained).

When i run the code, the random y positions appear positioned randomly for a moment, then all of the Zoog objects bounce to the top of the screen and stay in a line straight across.

What is happening? The Zoog objects should remain in their initial random y position…

I have tried hard coding in numbers instead of using “random”, but the same results each time.


Here is the code:

Zoog[] zoogies = new Zoog [100];

void setup(){
  size(400,400);
  for (int i = 0; i < zoogies.length; i++){
    zoogies [i] = new Zoog (random(width), random(height), 30, 30, 8);
  }
}
void draw(){
  background(255);
  for (int i = 0; i < zoogies.length; i++){
    zoogies[i].display();
    zoogies[i].jiggle();
  }
}
class Zoog {

  float x;
  float y;
  float w;
  float h;
  float eyeSize;

  Zoog (float tempX, float tempY, float tempW, float tempH, float tempEyeSize) {
    x = tempX;
    y = tempY;
    w = tempW;
    h = tempH;
    eyeSize = tempEyeSize;
  }
  void jiggle() {
    x = x + random(-1, 1);
    y = y + random(-2, 2);

    x = constrain (x, 0, width);
    y = constrain (y, 50, height);
  }
  void display() {
    for (float i = y - h/3; i < y + h/2; i += 10) {
      stroke(0);
      line(x-w/4, i, x+w/4, i);
    }
    ellipseMode(CENTER);
    rectMode(CENTER);

    //Zoog's body
    stroke(0);
    fill(175);
    rect(x, y, w/6, h);

    //Zoog's head
    stroke(0);
    fill(255);
    ellipse(x, y-h, w, h);

    //Zoog's eyes
    fill(0);
    ellipse(x-w/3, y-h, eyeSize, eyeSize*2);
    ellipse(x+w/3, y-h, eyeSize, eyeSize*2);
    
    //Zoog's legs
    stroke(0);
    line(x-w/12, y+h/2, x-w/4, y=h/2+10);
    line(x+w/12, y+h/2, x+w/4, y=h/2+10);
  }
}
1 Like

in the last lines of the class there is (twice) a = instead of a - which destroys y

Remark

That was hard to spot

  • I had to comment out different parts of the code one after the other and suddenly the y worked so I knew that part was guilty
3 Likes

You’re correct, that took care of the problem,
Thank you so much @Chrisir!

1 Like