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

时间:2016-09-05 16:08:21

标签: coordinates distance calc

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

e.g。假设locA和locB之间的距离是2500. locNew应该始终是距离为300的位置,并且应该位于locA和locB的行上。

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

我尝试了这个,但它返回了一个不在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)

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

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

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

2 个答案:

答案 0 :(得分:1)

我相信这应该有效:

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)

很抱歉,如果这不能回答你的问题,我不完全确定你的意思是“非数学形式”

答案 1 :(得分:0)

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

-- 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#