无限2D平面中点的Tile索引计算问题(适配负坐标)
Fixing Negative Coordinate Tile/Sector Index Calculation
It looks like the issue here is likely integer division behavior in C# messing up your negative coordinate calculations. Let me break this down:
The Root Problem
If your cellSize is an integer type (like int) and you're dividing an integer coordinate (from p_position.x/z) by it, C# performs integer division—this truncates towards zero instead of a full floating-point division.
For example, with cellSize = 300 and p_position.x = -10:
- Integer division:
-10 / 300 = 0(truncated towards zero) Mathf.FloorToInt(0)gives0, which doesn't match your expected-1
The Fix
You just need to ensure you're doing floating-point division instead. Convert cellSize to a float explicitly before dividing, so you get the precise decimal value to floor correctly:
public static Sector GetCurrentSector(Vector3 p_position) { // Convert cellSize to float to force floating-point division float floatCellSize = cellSize; int x = Mathf.FloorToInt(p_position.x / floatCellSize); int z = Mathf.FloorToInt(p_position.z / floatCellSize); return new Sector(x, z); }
Or a more concise version:
public static Sector GetCurrentSector(Vector3 p_position) { int x = Mathf.FloorToInt(p_position.x / (float)cellSize); int z = Mathf.FloorToInt(p_position.z / (float)cellSize); return new Sector(x, z); }
Why This Works
- Floating-point division of
-10 / 300fgives-0.0333... Mathf.FloorToIntcorrectly rounds down to the nearest integer (which is-1for negative values between 0 and -300)- For your example coordinate
(-10, 10), this will returnSector(-1, 0)exactly as you expect.
Additional Test Cases
p_position.x = -300:-300 / 300f = -1→FloorToInt(-1) = -1(correct, boundary of the-1sector)p_position.x = -299.99f:-299.99 / 300f ≈ -0.9999→FloorToInt(-0.9999) = -1(correct, falls within the-1sector)p_position.x = -300.1f:-300.1 / 300f ≈ -1.0003→FloorToInt(-1.0003) = -2(correct, falls within the-2sector)
内容的提问来源于stack exchange,提问作者Tamil Ninja
相关产品推荐
相关产品推荐

