I'm trying to use decent OOP approach to getting objects to rotate individually within the cells of a grid. My current result is rotating all objects around the 0, 0 reference point instead of each within it's own cell.
Of course, what's needed is a correct translate function, but when I try to apply this in the innerSquare function translate(x, y); - this leads to even more bizarre behavior.
I'm still at early stage learning - any help would be appreciated!
The code can be viewed here: https://editor.p5js.org/knectar/sketches/BJpI5_BG4
Or directly:
var cols, rows;
var w = 50;
var grid = [];
function setup() {
createCanvas(400, 400);
// load the col / row vars with values that dynamically read from the canvas.
cols = floor(width/w);
rows = floor(height/w);
// load the the array with generic row and column values
for (var j = 0; j < rows; j++){
for (var i = 0; i < cols; i++){
// And for each, create an object instance based on the Shape class.
var shape = new Shape(i,j);
grid.push(shape);
}
}
}
function draw() {
background(51);
frameRate(2);
// draw grid (outer squares)
for (var i = 0; i < grid.length; i++) {
grid[i].outerGrid();
}
// draw inner squares
for (var i = 0; i < grid.length; i++) {
grid[i].innerSquare();
}
}
function Shape(i, j) {
this.i = i;
this.j = j;
var x = this.i*w;
var y = this.j*w;
this.outerGrid = function () {
push();
stroke(200, 0, 255);
noFill();
rect(x, y, w, w);
translate(x, y);
pop();
}
this.innerSquare = function () {
// translate(x, y);
noFill();
stroke(150, 0, 255);
rect(x+10, y+10, w-20, w-20);
rotate(radians(frameCount));
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>