查找其他两个位置之间的位置

find location between two other locations

我正在尝试在两个已经存在的位置 (x,y,z) 之间找到一个新位置 (x,y,z)。

例如假设 locA 和 locB 之间的距离是 2500。locNew 应该始终是距离为 300 的位置,并且应该在 locA 和 locB 的线上。

我没有问题找到 locA 和 locB 之间的中点,但我一直在努力寻找针对这种特定情况的 locNew。

我试过了,但是 returns 一个点不在从 locA 到 locB 的直线上:

locA = {x = 400, y = 400, z = 400}
locB = {x = 1200, y = 1200, z = 1200}

--this is wrong somehow
locNew_x = (locB.x+locA.x)-(locB.x-300)
locNew_y = (locB.y+locA.y)-(locB.y-300)
locNew_z = (locB.z+locA.z)-(locB.z-300)
locNew = {x = locNew_x, y = locNew_y, z = locNew_z}

--draws a line between two objects
DrawLine(locA, locNew)

编码语言并不重要,因为计算在大多数语言中应该看起来 'almost' 相同,请记住,我正在寻找非数学形式的解决方案。

更新: 如果 x、y、z 相同,则标准解决方案有效,但如果它们不同,则如下例所示。

locA = {x = 1475, y = 95, z = 838}
locB = {x = 2226, y = 110, z = 1190}

我相信这应该有效:

locA = {x = 400, y = 400, z = 400}
locB = {x = 1200, y = 1200, z = 1200}

scalar = 300/distance(locA,locB);    --target distance/existing distance

locNew_x = locA.x + (locB.x - locA.x) * scalar
locNew_y = locA.y + (locB.y - locA.y) * scalar
locNew_z = locA.z + (locB.z - locA.z) * scalar
locNew = {x = locNew_x, y = locNew_y, z = locNew_z}


DrawLine(locA, locNew)

抱歉,如果这不能回答您的问题,我不太确定您所说的 "a non mathematical form"

是什么意思

我认为这可能对您有所帮助:

-- Substract vectors
function subVectors(vector_A, vector_B)
    return {x = (vector_A.x - vector_B.x),
            y = (vector_A.y - vector_B.y),
            z = (vector_A.z - vector_B.z)}
end

--- Calculate length of vector
function vectorLength(vector_A)
    return math.sqrt(
        (vector_A.x * vector_A.x) +
        (vector_A.y * vector_A.y) +
        (vector_A.z * vector_A.z)
    )
end

-- Convert to unit vector
function toUnitVector(vector_A)
    local ln = vectorLength(vector_A)
    return {x = (vector_A.x / ln), y = (vector_A.y / ln), z = (vector_A.z / ln)}
end

-- calculate position of vector which is on the line between A and B and 
-- its distance from B point equals `distance`
function distancedVector(vector_A, vector_target, distance)
    local vec = subVectors(vector_A, vector_target)
    local unitVec = toUnitVector(vec)

    return {
        x = (vector_target.x + unitVec.x * distance),
        y = (vector_target.y + unitVec.y * distance),
        z = (vector_target.z + unitVec.z * distance)
    }
end

local locA = {x = 0.0, y = 0.0, z = 0.0}
local locB = {x = 900.0, y = 900.0, z = 900.0}

local ret = distancedVector(locA, locB, 10)

print(string.format("x: %f\ny: %f\nz: %f\n", ret.x, ret.y, ret.z))

输出:

x: 894.226497
y: 894.226497
z: 894.226497

相关:Move point to another in c#