How to Snap to a Grid

Материал из Поле цифровой дидактики

Many projects require that a sprite be snapped to a grid. This is most common in board game simulations, but can be applicable in other projects. The following article will present the script that will take a set of coordinates and report them as the closest coordinate on an imaginary grid.



The most common use is in games such as Minesweeper, chess, or others which involve a gridded board. The mouse is most often used to detect user input. The following script will snap the sprite to a grid:

when gf clicked
set x to ((round ((mouse x) / (width))) * (width))
set y to ((round ((mouse y) / (width))) * (width))

Optionally, the "set x to ()" and "set y to ()" blocks can be compressed into a "go to x: () y: ()" block.

To shift the grid left, right, up, or down, simply subtract the change from the respective dimension, and add it at the end of the operation. Here is the general script:

when gf clicked
set x to (((round (((mouse x) - (shift right)) / (width))) * (width)) + (shift right))
set y to (((round (((mouse y) - (shift up)) / (width))) * (width)) + (shift up))


If you're receiving your inputs from the keyboard, the coordinates remain the same, but, instead of using the mouse coordinates, you use the un-snapped x and y value, and then snap the sprite using those points; this means that the sprite's "real" x and y positions are generally stored as variables. For example:

when gf clicked
go to x: ((round ((x) / (width))) * (width)) y: ((round ((y) / (width))) * (width))