Making A Mouse Object Follow A Grid

A lot of games arrange game objects in grids. In fact, if you use Stencyl, you may have already noticed tiles are placed on a grid. I probably don’t have to go into too much detail as to why this is useful; its applications are plentiful.

So in this tutorial, I’m going to explain how to make a cursor or some other object “follow” your mouse while positioning itself according to the grid. Its actually rather simple; it just involves some simple math. Its short and sweet (so much so I don’t see much need to have headings), so let’s get to it then.

First in your code, decide whether or not you want to hide your in-game mouse. You may want the mouse to show on top of your cursor object, since the cursor will be moving only when you pass the mouse from space to space. Otherwise, hide it with the block found under User Input.

Next, pull out two position setters for your actor under Actor >> Position. Set one to X, and set one to Y.

Now comes the math. For this tutorial, we will use our tile dimensions as our grid. Here is what it will do (all blocks are found under Numbers & Text >> Math):

Divide mouse position x/y by your tile width/height. For instance, if our tile width is 10 and our mouse is at 25, we will get 2.5.

Take the floor of this calculation to remove any decimal places. Our 2.5 becomes 2. This essentially means we want to be 2 tiles over from the left of our screen for cursor placement. We dont wan’t to be 2.5 tiles over because we want to snap to the grid.

Multiply it by tile width/height. Convert our tiles from the left (2) back into pixels from the left (20).

Stick these in your position setters (don’t forget to match up your x’s and y’s), and voila. That’s all there is to it. You can see an example pic below of what your code should look like:

For added flexibility, you could replace tile width/height with attributes (if you put this in a behavior) and modify the values if you are not using a tile-based grid.