Search code examples
javascriptp5.js

Objects not arranged how I expected them to


I'm working on a p5.js project for class, and I ran into an issue while coding.

Right now, the code is supposed to generate 5 objects under the class Building, and then use that to draw 5 equally spaced boxes in a straight line, but for some reason, the boxes are not equally spaced, and I have no idea why.

Any help is greatly appreciated.

//basically, I want this code to generate 5 equally spaced rectangular prisms centered on the screen

let buildings = []

class Building {
  constructor(spot, h, w) { //spot is basically how far along the line of buildings a given building should be (0 is at the beginning, 4 is at the end because it counts from 0), h and w are height and width, adn are currently the same for all objects for simplicity
    this.spot = spot;
    this.h = h;
    this.w = w;
  }

  create() {
    box(this.w, this.h, this.w)
    translate((this.spot*160)-200, 0, 0) //this is the line that is giving me issues. it SHOULD be moving the boxes so that they are equally spaced from each other, but instead they give me this weird almost exponential spacing. additionally, if the y or z are changed, a similar thing occurs, with the boxes just not being where youd expect them to be
  }
}

function setup() {
  createCanvas(800, 600, WEBGL);
  for (let i=0; i<5; i++) { //add 5 building objects to the array
    buildings[i] = new Building(i, 400, 40)
  }
}

function draw() {
  background(220);

  for (let Building of buildings) { //draw the 5 buildings
    Building.create()
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.js"></script>


Solution

  • translate() accumulates. Use push() before translate() to save the transformation matrix, then pop() afterwards to restore it.

    Also, translate() first, then draw your boxes.

    class Building {
      constructor(spot, h, w) {
        this.spot = spot;
        this.h = h;
        this.w = w;
      }
    
      draw() {
        push();
        translate(this.spot * 160 - 200, 0, 0);
        box(this.w, this.h, this.w);
        pop();
      }
    }
    
    const buildings = [...Array(5)].map((_, i) =>
      new Building(i, 400, 40)
    );
    
    function setup() {
      createCanvas(800, 600, WEBGL);
    }
    
    function draw() {
      background(220);
    
      for (const building of buildings) {
        building.draw();
      }
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js"></script>

    spot may not be the clearest variable name.