How to Snap to a Grid

Материал из Поле цифровой дидактики
Версия от 14:26, 12 августа 2022; Patarakin (обсуждение | вклад)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)

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.

Mouse

Шаблон:Note

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))

Keyboard

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
forever
go to x: ((round ((x) / (width))) * (width)) y: ((round ((y) / (width))) * (width))