Hi folks. As far as I’ve know there is currently no way in the Editor to snap objects to a grid. Tilemaps might work as an alternative in some cases, but not always. I’ve done some googling and apparently it is a feature that has been requested a few times, so I thought I could share my own workaround. Please bear in mind that I’m still new to Defold, so this is a really simplistic fix. Its good enough for me, but it might not work in some special cases and there are probably better ways to do it.
local cellSize = 32
function init(self)
local posX = go.get(".", "position.x")
local posY = go.get(".", "position.y")
go.set(".", "position.x", round(posX/cellSize) * cellSize)
go.set(".", "position.y", round(posY/cellSize) * cellSize)
end
function round(n)
return n % 1 >= 0.5 and math.ceil(n) or math.floor(n)
end
Take into account this only works when objects are created, if you need to align them again while running the game you need more code for that. This just saves time while fiddling with dirty prototypes by not having to write exact coordinates for each object. Thanks to user Gmanicus as I got the ROUND function from him.
EDIT: added a couple of pictures to show what it does.
EDIT2: Look below for a much better version by Britzl himself!