gmlgame-maker-languagegame-maker-studio-2

I want to know how transformed "a-(a%b) " to "a&(~b)" (snapping grid formula)


When I searching about Snapping grid function. Actually it is Tile Collide.(You maybe know I learning GMS2 because of tags..)

It is not important for my question.

Cut to the chase, I learned about this formula.

pos.x - (pos.x % gridwidth)  <- this is number calculation.

It worked well what I want to. And I found different formula.

This formula is working for collision of obj and tiles.

(pos.x)&~(gridwidth-1)    <- this is binary calculation.

And It has same work. What happen?? I can't understand how these formula are transformed..

Actually I understand '&' has same work with subtract. But I don't understand others.

for example

var f1,f2;
var pos_x = 102;
var gridwidth = 64; // It must be even power of 2.
f1 = pos_x - (pos_x % gridwidth);
f2 = (pos_x)&(~(gridwidth-1));


Solution

  • These two formulas are only equivalent if gridwidth is an even power of two, like 128, 256, 2048, etc.

    In either case, pos.x - (pos.x % gridwidth) is doing a floor back to an even multiple of gridwidth, "snapping" to the start of that grid cell, where the grid consists of cells of width gridwidth.

    If you can assume gridwidth is an even power of 2, then (pos.x)&~(gridwidth-1) is doing the same thing. Basically, given this assumption, every value in one grid cell will only differ in its lower order bits...the bits below the gridwidth bit. This code is just clearing those bits, thereby calculating the result to a be an even multiple of gridwidth, which will be the first position in that cell of the grid.