|Please expand this article or section. You can help by talk page. (August 2018)if you are an editor. More information might be found in a section of the|
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.
|Note:||The variable "width" refers to the width of each grid square.|
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 forever 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 forever 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 sprites "real" x and y positions are generally stored as variables. For example:
when gf clicked forever go to x: ((round ((x) / (width))) * (width)) y: ((round ((y) / (width))) * (width))