Entity Snapped to Grid with mouse movement


(Gil) #1

On the help topics, I stumbled upon a thread involving a user with a similar problem as I currently have. Which is that in my project I’d like movement of my entities snapped to a grid. Except movement in that thread is based on key input, like WASD or arrows.

My entities need to be draggable and droppable etc. Although I have completed the first step of making them draggable and droppable I still cannot restrict their movement to a grid or perhaps certain locations on the screen. Please help!


(Kyuur) #2

What you are going to want to do, is when they are ‘dropped’, figure out what grid coordinate they should be on, and then set their actual position to that coordinate times the grid tile size.

var xCoordinate:int = Math.floor(x / tileWidth)
var yCoordinate:int = Math.floor(y / tileHeight)
		
x = xCoordinate * tileWidth;
y = yCoordinate * tileHeight;

So if your grid is 32x32 per tile, and your entity is at (37, 36), it will snap to (32, 32).


(Gil) #3

I actually have a problem checking for grid height/width, I can’t access those parameters inside my entity classes. Can I just provide some of my code?


(Kyuur) #4

You have two options:

  1. You can hardcode a const value in.

  2. Make the Grid public in it’s entity. Then you can access it from the world:

    myGridEntity.myGrid.tileHeight

Pass this to each Entity class that needs it in their constructor. If you’re still having trouble feel free to post some code and a description of the exact situation and I’ll take a look!


(Gil) #5

FIXED! :slight_smile: Thank you!!!

I declared the tileWidth and tileHeight of my grid as public static Integer variables in my grid class. I plugged in your code to my Drag&Drop Class specifically to “onEndDrag()” which is a function depicting the event where the mouse is released and the entity is essentially “dropped” :

var xCoordinate:int = Math.floor(x / tileWidth)
var yCoordinate:int = Math.floor(y / tileHeight)

x = xCoordinate * tileWidth;
y = yCoordinate * tileHeight;

But instead of using tileWidth and tileHeight i just called the corresponding variables from my Grid Class into my Drag&Drop Class.

Works like a charm, thanks again!


(Jacob Albano) #6

Not specifically related to this problem, but you might want to declare tileWidth and tileHeight as const or read-only. It might save you from awkward bugs if you accidentally assign to one of them. My personal rule of thumb is that all globally-accessible data is immutable. It makes debugging a lot easier when you don’t have to worry about things getting set in the wrong places.