# Snapping to a grid.

This topic is 4813 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello. Im working on my level editor and im currently trying to implement the "snapping" of objects to the grid. But i cant figure out how to know when a object should snap. I have my grid, which i know the size of. I also know the resolution of the grid. So if the grid is say 64x64 units large. And its subdivided into 8x8 squares. And an object is at position x,y and is currently beeing translated along the x-axis. Then how do i calculate if the object is close enough to a "line" to snap to it? Anyone know? Thanks in advance. // Peter B

##### Share on other sites
Here's a quick explanation. Think of the intersecting points where each grid is devided, that is where you want your points to snap to right (of course I know you already know that :))? Now think of that point as being at the center of a box the same size as your grid resolution. When your cursor, or whatever enters that box, set the point to the intersection of the lines at that grid location.

I hope that was clear enough. Post back if you have any questions.

##### Share on other sites
First of all I think you'll need to store the position of the mouse where it was clicked and where it is now. Then you'll perform the operation on the object depending on those two points. Let's say we're translating: you'll add a vector (equal to current mouse minus initial mouse positions) to the object's position. I would suggest you don't actually change the position but use a temporary position (for unexpected errors caused by the user).

After that's done you'll do the snapping. You can snap to vertical or horizontal grid line and grid point. For the horizontal lines: let ty be your temporary y coord and ly be the line y coord. If abs(ty-ly) < treshold then you set ty=ly; Same for vertical lines only use the x coordinates. For points check both y and x coordinates.

To determine the grid lines where you could potentially snap just take your temporary x and y coordinates and find the closest multiple of the grid size.

1. 1
Rutin
40
2. 2
3. 3
4. 4
5. 5

• 18
• 20
• 13
• 14
• 9
• ### Forum Statistics

• Total Topics
633365
• Total Posts
3011520
• ### Who's Online (See full list)

There are no registered users currently online

×