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):

  1. 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.
  2. 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.
  3. 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:

GridCursor

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.

Happy Stencyling!

Advertisements
Posted in Movement, Stencyl
One comment on “Making A Mouse Object Follow A Grid
  1. ridhwaan08 says:

    Hi Photon thanks for this.In some games you need to place the an actor on the grid how would you go about doing this.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: