processing

How would I snap a position to a rectangular grid?


I'm trying to make a midi-editor in processing and I need to have rectangular cells that you can click on to add a note there.

So far I've done googling but haven't found a result. What happens is when you click the further down the less accurate it gets.

I don't know what is going wrong and I've had this problem in the past but couldn't fix it.

Note: The cells are not square.


Solution

  • Here's code to snap the mouse coordinate to the center of the nearest rectangular grid cell, where cells are defined by width and height.

    int w = 48; // rectangle width
    int h = 24; // rectangle height
      
    int snapX = round(mouseX / w) * w + w/2; // '+ w/2' is offset to center of cell
    int snapY = round(mouseY / h) * h + h/2;   // '+ h/2' is offset to center of cell