【发布时间】:2015-04-19 20:44:34
【问题描述】:
我需要计算 3D 空间中两点之间的距离。我使用的坐标系是 Int64 来获取扇区,并且在每个扇区内 Int32 用于获取本地位置。所以本质上它是一个 Int96 位坐标系。
如果没有大量 if 语句检查边界,我不确定这将如何工作,因此可能有更聪明的方法。
谁能帮忙?
PS! Double 中的精度损失是可以接受的。我不能使用不安全的代码。 BigInteger 不是一个选项,因为代码必须在 Unity 中运行。
样本可以是:
public struct SectorPos
{
public readonly Int64 X;
public readonly Int64 Y;
public readonly Int64 Z;
public SectorPos(Int64 x, Int64 y, Int64 z)
{
X = x;
Y = y;
Z = z;
}
}
public struct LocalPos
{
public readonly Int32 X;
public readonly Int32 Y;
public readonly Int32 Z;
public LocalPos(Int32 x, Int32 y, Int32 z)
{
X = x;
Y = y;
Z = z;
}
}
struct Pos
{
public readonly SectorPos Sector;
public readonly LocalPos Local;
public Pos(SectorPos sector, LocalPos local)
{
Sector = sector;
Local = local;
}
}
void Test()
{
// Should be 1:
Double d1 = Distance(new Pos(new SectorPos(0, 0, 0),
new LocalPos(Int32.MaxValue, 0, 0)),
new Pos(new SectorPos(0, 1, 0),
new LocalPos(Int32.MinValue, 0, 0)));
// Should be -1: (EDIT: Should be 1 of course)
Double d2 = Distance(new Pos(new SectorPos(0, -2, 0),
new LocalPos(Int32.MaxValue, 0, 0)),
new Pos(new SectorPos(0, -3, 0),
new LocalPos(Int32.MinValue, 0, 0)));
// Should be Int32.MaxValue+1:
Double d3 = Distance(new Pos(new SectorPos(1, 0, 0),
new LocalPos(Int32.MaxValue, 0, 0)),
new Pos(new SectorPos(3, 0, 0),
new LocalPos(Int32.MinValue, 0, 0)));
}
【问题讨论】:
-
为什么不使用
BigInteger而不是将定位划分为扇区和本地? -
抱歉忘了说代码也必须在 Unity 上运行(没有 BigInteger)。不使用 BigInteger 的第二个原因是我需要两个位置层,因此将它们作为单独的数字保存在结构中很有用。 IE。大多数(本地)计算仅使用 LocalPos。