GML Grid Code

bodilliam

Member
Hi guys I am somewhat new to GM, and was wondering if there was a easy way to make a snap to grid. There is on Construct 3 and I was just interested in knowing. Thanks!
 

Cameron

Member
You can divide by cell size, floor it, and then multiply it by cell size and that will take you to the top left of the grid cell.
For example if your grid cells are 32px and the x coordinate was 12356. You can divide (12356/32) which equals 386.125, then floor that to 386 and re-multiply back out at (386 * 32) which would equal 12352. Doing the same thing for the y coordinate would result in snapping to the top left corner of the grid cell.

Here's an example of code that would store the snapped coords in local variables.
GML:
var _cell_size = 32;
var _x = floor(x/_cell_size)*_cell_size;
var _y = floor(y/_cell_size)*_cell_size;
 
Last edited:

Roman P.

Member
@bodilliam fyi the div keyword will automatically floor it so this code is doing the same thing as my code, only difference is the flooring is happening internally by yoyo.
True. I just figured it out that way first, tbh I always forget which side of div takes what lol so might switch. :D Wonder if there's much performance difference.
 

Cameron

Member
True. I just figured it out that way first, tbh I always forget which side of div takes what lol so might switch. :D Wonder if there's much performance difference.
There wouldn't be a substantial performance difference. It's just a matter of preference/habit which one you use. Sometimes the yoyo internal stuff can throw you off and cause issues down the road in your project that can be hard to troubleshoot though. For example, hypothetically if you didn't know that the div keyword floored to an integer and you used it expecting it to only act as a "/" symbol, then down the road you could have unexpected behavior in your game that could take time to troubleshoot. That's the main knock on the internally handled code from the game engine anyhow.
 
Top