I am trying to create a hexagon made out of hexagon cells in p5.js.
I would like the algorithm to receive the following as input:
This is the code I have so far but it is not drawing the shape the way I want to.
// declare fixed variables
let diam = 30;
let total_hex = 30;
let diagonal = 7;
let first_row = 4;
let side = first_row;
// declare dependent variables
let radius = diam / 2;
let upper_half = side - 1;
let rows = upper_half + side;
function setup() {
createCanvas(700, 700);
}
// draw
function draw() {
background("#ffae5");
noFill();
strokeWeight(2);
stroke("#ffb703");
// start counters
// row_counter = rows;
counter = 0;
row_cells = first_row;
push();
translate(200, 200);
for (let j = 0; j < rows; j++) {
for (let i = 0; i < row_cells; i++) {
push();
translate(-j * (radius + radius / 2 + radius / 4), 0);
if (diagonal > i) {
console.log(diagonal, i);
push();
translate(i * 2 * diam - (i * radius) / 2, 3 * j * (diam / 2));
polygon(0, 0, diam, 6);
pop();
}
pop();
}
if (rows < j) {
row_cells -= 1;
}
if (rows > j) {
row_cells += 1;
}
}
pop();
}
function polygon(x, y, radius, npoints) {
let angle = TWO_PI / npoints;
beginShape();
for (let a = 0; a < TWO_PI; a += angle) {
let sx = x + sin(a) * radius;
let sy = y + cos(a) * radius;
vertex(sx, sy);
}
endShape(CLOSE);
}
Specifically, the hexagons from the bottom half of the shape appear to be shifted by some parameter I still can't figure out. Here's the link to the p5.js online editor.
What am I missing here? Thanks!
I logged i, j at each cell to determine the position.
Now if you look at the cells you want to remove, you will see that these cells are: i < 3 && j > 3 && j - i > 3.
So if you simply want to remove these cells, you could change your if (diagonal > i) to if (diagonal > i && !(i < 3 && j > 3 && j - i > 3))) or parametrize that 3 to be a dependent variable to Math.floor(diagonal/2) to make something like:
//declare fixed variables
let diagonal = 7;
...
//declare dependent variables
const bottomLeftThreshold = Math.floor(diagonal/2);
...
const bottomLeft = i < bottomLeftThreshold && j > bottomLeftThreshold && j - i > bottomLeftThreshold
if (diagonal > i && !(bottomLeft))
...
Now the code is much more readable and modularized.