Skip to main content
GameDev.net gamedev.net
🔒 Locked

Snapping to a grid.

Started by peter_b Sep 14, 2005 at 9:10 AM 1 replies 650+ views
Original Post
peter_b
peter_b
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
Shields up! Rrrrred alert!
WhatEver
WhatEver
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.
Ilici
Ilici
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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.