I am attempting to divide my game world into Sectors/tiles. And identify the tile where the player/object is at depending on the player/object position. I do not have a limited world size, so the world could be of any size. The tile size is defined and constant. So, the entire world is divided into square tiles of a given dimension.
Example: If I am dividing my world into equal sized square tiles of, say 300x300.
- If the player is within positions (0,0) to (300,300), the tile number should be (0,0)
- If the player is within positions (0,0) to (300,-300), the tile number should be (0,-1)
- If the player is within positions (-300,0) to (-600,300), the tile number should be (-2,-0)
More example inputs and outputs:
Player position is (10,10), tile number should be (0,0)
Player position is (-10,10), tile number should be (-1,0)
Player position is (10,-10), tile number should be (0,-1)
Player position is (-10,-10), tile number should be (-1,-1)
Player position is (1,1), tile number should be (0,0)
Player position is (1,-1), tile number should be (0,-1)
Player position is (-1,1), tile number should be (-1,0)
Player position is (-1,-1), tile number should be (-1,-1)
Player position is (-450,100), tile number should be (-2,0)
Player position is (450,100), tile number should be (1,0)
Player position is (-450,-100), tile number should be (-2,-1)
Player position is (450,-100), tile number should be (1,-1)
I have the below code, which seems to work correctly only when X/Z is positive. Once it is on the negative side of X/Z, i am not sure how i could calculate the position.
public static Sector GetCurrentSector(Vector3 p_position)
{
int x = Mathf.FloorToInt(p_position.x / cellSize);
int z = Mathf.FloorToInt(p_position.z / cellSize);
return new Sector(x, z);
}
I have checked the below questions, which seemed to be related to mine:
- Dividing a 2D array into boxes - Has the exact same flaw as mine
- getting rectangular coordinates of tiles of a 2D map - Has the exact same problem as mine
- How to create 3D tile maps using a Plane object divided into tiles? - Does not seem to be the same problem
- Convert 2d game world coordinates to screen position - Does not seem to be the same problem
- Converting from world coordinates to tile location - Seems to be a different issue
Note: I am also not sure what this problem is called! So, it makes it very difficult for me to search. My search led me to multiple places related to circles, radius, points within circle etc.,