I've been working in the p5js editor on a project where I am trying to visualize a 2D array using squares. The goal is to have a square change color via mousePressed() based on the mouse coordinates relative to the square. However, I'm encountering an issue where the square that changes color is not the one I expect.
After logging the node that I click, it appears to be correct. But the visualization of the 2D array seems to be off.
The grid consists of a 3x3 arrangement of square x's like this:
x x x
x x x
x x x
My expectation was that if I clicked on the top left and then the top middle square, they would change color to blue as follows:
o o x
x x x
x x x
However, when I actually click on the top left followed by the top middle square, the result is:
x o o
x x x
x x x
It seems that clicking on a square causes the adjacent square to change color instead of the intended one.
An example can be found in the p5.editor at the following link:
let arr = [];
function setup(){
canvas = createCanvas(200, 200);
for(var j = 0; j < 3; j++){
var inArr = [];
for(var i = 0; i < 3; i++){
var rect = new Rect(i,j);
inArr.push(rect);
}
arr.push(inArr)
}
}
function draw(){
for(var i = 0; i < arr.length; i++){
for(var j = 0; j < arr[i].length; j++){
arr[i][j].show()
}
}
}
function mousePressed(){
arr.forEach(function(e, index){
e.forEach(function(d,index2){
arr[index][index2].clicked()
});
});
}
function Rect(i,j){
this.fill = 'red'
this.i = i;
this.j = j;
this.x = i * 20
this.y = j * 20
this.clicked = function(){
let x1 = this.x, x2 = x1 + 20,
y1 = this.y, y2 = y1 + 20;
if((mouseX>x1&&mouseX<x2)&&(mouseY>y1&&mouseY< y2)){
console.log(this)
this.fill = 'black'
}
}
this.show = function(){
rect(i*20,j*20,20,20)
fill(this.fill)
stroke('blue')
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>