如何在负数空间中得到这样的相对坐标呢?

How can I get such relative coordinates even in negative number space?

本文关键字:相对 坐标 空间      更新时间:2023-10-16

想象一个简单的二维整数网格。它被一个更大的整数网格划分成块。给出了相等块的尺寸。

要从全局坐标中获得块,我可以简单地将坐标除以块大小并去掉小数点:chunk.x = global.x / chunksize.x。这只适用于无符号数,因为负坐标不会四舍五入到正确的方向。因此,我手动向下四舍五入:chunk.x = (int)floor((float)global.x / chunksize.x)。这工作得很好,但这里有另一部分。

我还想从全局坐标中计算相对于包含块的坐标。对于无符号数,我只使用余数:local.x = global.x % chunksize.x;。但这对负坐标不起作用,因为负块的局部坐标不被镜像。

我怎么能计算局部坐标,即使在负数空间没有计算块之前?

This

const int M = 100000;
//chunk.x = (global.x + M*chunksize.x) / chunksize.x - M;
local.x = (global.x + M*chunksize.x) % chunksize.x;

应该比与浮点数的转换快得多。

//chunk.x = global.x / chunksize.x;
local.x = global.x % chunksize.x;
if (local.x < 0) {
     //chunk.x--;
     local.x += chunksize.x;
}

对于负面结果,将块大小添加到它们(这使它们为正)。如果你再取模,你会得到一个同样适用于正和负global.x的表达式:

local.x = ((global.x % chunksize.x) + chunksize.x) % chunksize.x;