How to click on a Cell?

Hi, I'm using Javascript, p5.js, and Daniel Shiffman's tutorial to create a visual representation of an A* search algorithm.

I've attached a sample grid with this post.

Is it possible to click on any cell of the grid to print out it's attributes? Based on Daniel Shiffman's other tutorial on how to click on objects, I understand I have to create 2 functions that activate and execute respectively. I understand how to do this with a circle because a circle has a radius.

But, I don't understand how to do this with a cell because I only have access to it's coordinates. I can't seem to click on each each cell distinctively without a length. The following are codes for the 2 functions:

// function that activates
function mousePressed(){
  for (var i = 0; i < cols; i++) {
        for (var j = 0; j < rows; j++) {
            grid[i][j].clicked();
        }
    }
}

// function that executes for each cell object
this.clicked = function() {
  var d = dist(mouseX, mouseY, this.i, this.j);
  if(d < 1){
    console.log("f", this.f);
  }
}

I'd appreciate any guidance to my thinking. Thank you so much in advance.

(https://forum.processing.org/two/uploads/imageupload/297/5RJSVC8QGUDG.png "3.1")

Tagged:

Answers

  • There are two shapes that are super easy to know if they have been clicked. Detecting a click on anything else is sort of a pain.

    The first good shape is a circle. As you have said, you can detect the click based on how far it is from the circle's center, and compare that to the circle's radius.

    The other good shape is a rectangle that hasn't been rotated. Since you can determine the x and y positions on the sides of the rectangle, you can make sure that the x and y positions of the click are bound between the sides.

    if( x<mouseX && mouseX<x+w && y<mouseY && mouseY<y+h ){
    

    Assuming that your Cells are rectangles, you can check each of them in turn to see if this condition is true. If it is, then you know which one has been clicked, and can have it print out information about itself.

Sign In or Register to comment.