Locate a free-moving 2D object's position in a grid.
Ok, so I have a player object that can move freely in all directions, with no snapping to the above mentioned grid. I need to figure out in which square of the grid that object is.
The grid is not a game object itself currently, it's only meant to give a rough position of the player (GridX, GridY) for some other objects to use. It starts as (0,0) in the lower left corner of the screen (this is a static level) and increases in both axis across the screen. The grid divisions are square, and the size of each square is a fixed number of Unity units (I don't know how big it should be yet, sprites aren't in). The grid is also always only 10x4, and the player can only move within it (that part's easy enough, though).
I can't just do this with a big stack of ifs, there must be a better way.
Answer by ShadyProductions · Mar 15, 2017 at 01:43 PM
public Vector2 GetGridByPosition(float x, float y) {
return new Vector2(Convert.ToInt32(x),Convert.ToInt32(y))
}
This will return your Vector2 position of the grid. It should be pretty accurate. It rounds the given position to the nearest int.
Depending if your grids go as follows: 1,1 1,2 1,3 etc
Else, you'll have to adapt it to your grid size
I need to slightly adapt that if the grid is bigger than one Unity unit, but it gave away the logic I should use.