Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save dogboydog/c00ac89e8ee07428487de4bd5dc8121d to your computer and use it in GitHub Desktop.

Select an option

Save dogboydog/c00ac89e8ee07428487de4bd5dc8121d to your computer and use it in GitHub Desktop.
Tiled JS script - Snap objects to pixel coordinates
/**
* Snap everything in the map to integer positions automatically when a map is saved.
*/
const actionName = "Integer Position Snap";
var action = tiled.registerAction(actionName, function (action) {
let map = tiled.activeAsset;
map.macro("Integer Position Snap", function () {
const snapObjectsOnLayer = function (objectLayer) {
{
if (!objectLayer.isObjectLayer) {
return;
}
objectLayer.objects.forEach(obj => {
obj.x = Math.round(obj.x);
obj.y = Math.round(obj.y);
if (obj.width) {
obj.width = Math.round(obj.width);
}
if (obj.height) {
obj.height = Math.round(obj.height);
}
obj.pos = Qt.point(Math.round(obj.pos.x), Math.round(obj.pos.y));
if (obj.polygon && obj.polygon.length >= 1) {
obj.polygon = obj.polygon.map(p => Qt.point(Math.round(p.x), Math.round(p.y)));
}
})
}
}
const snapRecursive = function (layer) {
if (layer.isObjectLayer) {
snapObjectsOnLayer(layer);
} else if (layer.isGroupLayer) {
layer.layers.forEach(snapRecursive);
}
}
map.layers.forEach(snapRecursive);
});
});
action.text = actionName;
function checkIfActionNeeded(savedAsset) {
if (!savedAsset.isTileMap) {
return;
}
tiled.trigger(actionName);
}
tiled.assetAboutToBeSaved.connect(checkIfActionNeeded);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment