问题
I am trying trying to find a new location(x,y,z) between two already existing locations (x,y,z).
e.g. lets say the distance between locA and locB is 2500. locNew should always be the location with distance 300 and should be on the line of locA and locB.
I have no issues finding the midpoint between locA and locB, but I keep banging my head trying to find locNew for this specific situation.
I tried this, but it returns a point that is not on the line from locA to 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)
Coding language is not important, since the calculation should look 'almost' the same in most languages, keep in mind that im looking for a solution in a NON mathematical form.
Update: standard solutions works if x,y,z is the same, but not if they are different like in the example below.
locA = {x = 1475, y = 95, z = 838}
locB = {x = 2226, y = 110, z = 1190}
回答1:
I think this might help you:
-- 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))
Output:
x: 894.226497
y: 894.226497
z: 894.226497
Related: Move point to another in c#
回答2:
I believe this should work:
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)
Sorry if this doesn't answer your question, I'm not exactly sure what you mean by "a non mathematical form"
来源:https://stackoverflow.com/questions/39334260/find-location-between-two-other-locations