You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无限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) gives 0, 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 / 300f gives -0.0333...
  • Mathf.FloorToInt correctly rounds down to the nearest integer (which is -1 for negative values between 0 and -300)
  • For your example coordinate (-10, 10), this will return Sector(-1, 0) exactly as you expect.

Additional Test Cases

  • p_position.x = -300: -300 / 300f = -1 → FloorToInt(-1) = -1 (correct, boundary of the -1 sector)
  • p_position.x = -299.99f: -299.99 / 300f ≈ -0.9999 → FloorToInt(-0.9999) = -1 (correct, falls within the -1 sector)
  • p_position.x = -300.1f: -300.1 / 300f ≈ -1.0003 → FloorToInt(-1.0003) = -2 (correct, falls within the -2 sector)

内容的提问来源于stack exchange,提问作者Tamil Ninja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 18:37:32