首页 > 解决方案 > 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.

标签: processing

解决方案


Example processing code to snap the mouse coordinates to the center of the nearest grid cell (where cell dimensions are defined by rectangle 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

推荐阅读