The simplest way to snap in 2D is %
. Define your grid step, then subtract the modulo of that from your current location to snap, no modulo for free motion.
int gstep = 10;
void draw(){
background(128);
if (keyPressed){
ellipse(mouseX, mouseY, 10, 10);
} else {
ellipse(mouseX - mouseX%gstep, mouseY - mouseY%gstep, 10, 10); // snap
}
lines();
}
void lines(){
for(int x=0; x<=width; x+=gstep) line(x,0,x,width);
for(int y=0; y<=height; y+=gstep) line(0,y,height,y);
}
This assumes your origin in 0,0, your step size is an integer, and your grid is whole-screen, but setting to an arbitrary range on the screen isn’t much more complicated. Good for basic sketches.
At a certain point, if you are, e.g. programming the game “Battleship” with two grids floating in screen, you might want to transition to an Object oriented example with a grid class.
The snap-down behavior, above, means that your mouse won’t be snapping to the closest point – it will be snapping to the closest point up-and-left. That may not be what you want. You can snap to closest in a simple way by adding a 0.49 step to your input. Try enabling and disabling the “change snap-down” line below to see the difference.
int gstep = 25;
void draw(){
background(128);
if (keyPressed){
ellipse(mouseX, mouseY, 10, 10);
} else {
ellipse(snap(mouseX, gstep), snap(mouseY, gstep), 10, 10); // snap
}
lines();
}
float snap(float input, float step){
input += (step*0.49); // change snap-down to snap-closest
float snapped = input - (input % step);
return snapped;
}
void lines(){
for(int x=0; x<=width; x+=gstep) line(x,0,x,width);
for(int y=0; y<=height; y+=gstep) line(0,y,height,y);
}