"Snap-to-grid" functionality

Hi,

I was wondering if anyone had any tips, advice of objects “snapping” to a grid so that they are aligned along some grid lines/etc. For instance, if I have a square grid and am dragging around a square and want it to only position along the grid lines.

Thanks,
DAT

Off the top of my head: take the object current X,Y and add the difference between that and the mouse X,Y (because you may not always have the mouse pointer right on the left and top edge of the object) and if that is greater than halfway across a grid cell move the object to the next grid cell X, same for the Y.

I would go for


alignedObjectX = (objectX%cellWidth)*cellWidth;
alignedObjectY = (objectY%cellHeight)*cellHeight;

ofcourse, you will have to store both the real (objectX/Y)and aligned(alignedObjectX/Y) coordinates of the object.

When you move the object, you modify the objectX/Y coords (and recalculate the alignedObjectX/Y).
When you render the object, you use the alignedObjectX/Y coords.

Wouldn’t you want the object position to then become the aligned position? I would think it would be confusing if you align something to a grid but the data is not aligned.

Dunno if that’s what you want. I had to implement this for my job, I created a form builder, but since the form was printable I had to make sure that the object was where it was on the screen as well as on the paper.

depends on what you were aligning.

I was trying to highlight the pitfall of re-aligning the x/y position after incremental relative movements.

e.g.

you have an object @ 0,0; it is aligned on a 20x20 grid.

each time you press an arrow key, the object is moved 5 pixels.
After each movement, the object is realigned, and is moved back to 0,0.
Hence, its impossible to move it :smiley:

If you were using an absolute movement system i.e. (moveDragged/mouseMoved) then you wouldn’t have to worry about such issues.

Maybe I was thinking ahead 2much :smiley:

Ah, didn’t think of that. Although if it were me and I needed to use the keyboard for example, I’d simple capture the keypress and move the component in my grid increments rather than worrying about relative alignment and stuff.

My turn to weigh in. For sucha too lid likely use Swing and
a scroll pane. If i did this then mouse clicks would be relative to
the origin of the drawing surface ragrdless of where Im scrolled.

Id then just do this for simplicity sake:

x = (mouse.x / gridCellWidh)*gridCellWidth;
y = (mouse.y /gridCellHeight)*gridCellHeight;

if you want top snap from the middle then you just need to add half a cell width like so:

x = ((mouse.x+gridCellWidth/2)/gridCellWidth)*gridCellWidth;
etc…