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.
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:
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.,
i suggest you to work with int and not FloorToInt and uses the integer division:
public static Sector GetCurrentSector(Vector3 p_position)
{
int x = (int)p_position.x / (int)cellSize;
int z = (int)p_position.z / (int)cellSize;
return new Sector(x, z);
}
my answer is not correct, your method was correct use matf.FloorInt is better that integer division for negative number.