Game Development Community

Grid align a sprite

by Andy Hawkins · in Torque Game Builder · 12/26/2006 (7:27 pm) · 3 replies

How do I grid align a sprite? I tried using this function but it doesn't work the way I expected it to.

The theory was to take the position of the sprite, divide it's position by the unit grid size, round off any remainder and multiply by the grid size to snap to grid.

Maybe I'm not using the mRound function properly, but it doesn't appear to snap the sprite to grid when I release it at all.

// snap to position
      // get current position
      %pos = %this.mySprite.getPosition();
      
      %x = getWord(%pos,0);
      %y = getWord(%pos,1);
      
      %x -= -87.678; // take top corner
      %y -= -62.852; // take top corner
      
      %x /= 32;
      %x = mRound (%x);
      %x *= 32;
      
      %y /= 32;
      %y = mRound (%y);
      %y *= 32;
      
      %x += -87.678;
      %y += -62.852;
      
      setWord(%pos,0,%x);
      setWord(%pos,1,%y);
      
      %this.mySprite.setPosition(%pos);

#1
12/27/2006 (10:01 am)
I believe setWord is supposed to work like this:

%pos = setWord(%pos,0,%x);
%pos = setWord(%pos,1,%y);
#2
12/27/2006 (10:04 am)
Ah yes, nice catch Matthew. Also, I would like to point out that you don't really have to mess with all that setWord since you're changing the whole vector anyway. You can just do:

%obj.setPosition(%x SPC %y);

which just builds a whole new vector for you. On top of that, setPosition is probably overloaded to accept

%obj.setPosition(%x, %y);

as well.
#3
12/28/2006 (1:37 pm)
Thanks guys this code worked ....

// snap to position
      // get current position
      %pos = %this.mySprite.getPosition();
      
      %x = getWord(%pos,0);
      %y = getWord(%pos,1);
      
      %x -= -87.678; // take top corner
      %y -= -62.852; // take top corner
      
      %x /= 32;
      %x = mRound (%x);
      %x *= 32;
      
      %y /= 32;
      %y = mRound (%y);
      %y *= 32;
      
      %x += -87.678;  // add top corner
      %y += -62.852;  // add top corner
      
      %pos = setWord(%pos,0,%x);      // <--- this bit was changed
      %pos = setWord(%pos,1,%y);
      
      %this.mySprite.setPosition(%pos);