Nested loop adjustable from slider

Viewed 44

I want to make a grid of squares which will be adjustable from two sliders, one for the width and the other for the height. I've managed somehow to make it work for the width of the grid but I have no luck for the height.

Below is the code:

let bubbles = [];
var slider, slider2 ;
function setup() {
 var canvas=createCanvas(windowWidth, windowHeight);
 slider = createSlider (10,260,260);
 slider2 = createSlider (10,260,260);
 for (var i=0; i<25; i++) {
    for ( var j=0; j<5; j++){
      var x = i * 260;
      var y=j*260;
   
    let b = new Bubble(x, y);
    bubbles.push(b);
    }
  }
}
function draw() {
  
  background(0);
var value = slider.value();
   for (let i = 0; i < bubbles.length; i++) {
    bubbles[i].show(i);
   
  }
}
class Bubble {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.brightness = (0);
    this.slider=slider.value();
     this.slider2=slider2.value();
  }

 show(i) {
   push();
    stroke(255);
   //noStroke ;
    strokeWeight(0.2);
    fill(this.brightness);
  this.x=((i/5) - ((i%5)/5) ) * slider.value();
      //this.y=((i/5) - ((i%5)/5) ) * slider2.value();
 

   translate(this.x, this.y);
 rect(0 ,0,260);
   pop(); 
  }
}

 
1 Answers

If this is the final product you're trying to reach then I don't recommend classes since there is a limited number. Tell me if there is anything that you want in specific and tell me what it is, also I can annotate and explain things for you.

var slider, slider2 ;
function setup() {
 var canvas=createCanvas(windowWidth, windowHeight);
 slider = createSlider (10,260,260);
 slider2 = createSlider (10,260,260);
}
function draw() {
  
 for(i = 0; i < width / slider.value(); i ++){
   for(j =0; j < height / slider2.value(); j ++){
     fill(255,i/slider.value() * 255 ,j / slider.value() * 255);
     rect(i * slider.value(),j * slider2.value(),slider.value(),slider2.value());
   }
 }
}

This is the edit with the classes and arrays:

var maxVal = 30;
var resX = 20;
var resY = 20;
var sliderX, sliderY;

var grid = [];
function setup() {
  
  for(i = 0; i < maxVal; i ++){
    grid[i] = [];
    for(j =0; j < maxVal; j ++){
      grid[i][j] = new Point(i,j);
    }
}
  
 var canvas=createCanvas(windowWidth, windowHeight);
 sliderX = createSlider (10,30,resX);
 sliderY = createSlider (10,30,resX);
}
function draw() {
  background(0);
  resX = sliderX.value();
  resY = sliderY.value();
  
  for(let i of grid){
    for(let j of i){
      j.display();
    }
  }
}

class Point{
  constructor(x,y){
    this.x = x;
    this.y = y;
  }
  display(){
    rect(this.x * resX,this.y * resY,resX,resY);
  }
}

if you're going to expand the maxVal to a very large number then I recommend only redrawing when a slider is changed instead of 60 times a second.

Related