# How to snap mouse to a shape/coordinate?

**URL:** <https://discourse.processing.org/t/how-to-snap-mouse-to-a-shape-coordinate/13414>\
**Category:** Coding Questions\
**Created:** [August 16, 2019, 2:23pm UTC](https://discourse.processing.org/t/how-to-snap-mouse-to-a-shape-coordinate/13414 "2019-08-16T14:23:05Z")\
**Posts on this page:** 1\
**Showing post:** 9

<div class="post-metadata">

**Author:** ![jeremydouglass](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jeremydouglass/32/20_2.png) [@jeremydouglass](https://discourse.processing.org/u/jeremydouglass)\
**Post date:** [August 18, 2019, 2:48pm UTC](https://discourse.processing.org/t/how-to-snap-mouse-to-a-shape-coordinate/13414/9 "2019-08-18T14:48:45Z")

</div>

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.

```auto
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.

```auto
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);
}

```

---

_[View the full topic](https://discourse.processing.org/t/how-to-snap-mouse-to-a-shape-coordinate/13414)._
