I'm trying to plot some points along a 3D line segment and could really use some help. In 2D, I've found success getting the angle of the line, the sine & cosine of the angle, and then adding the cosine & sine to the starting point of the line's x & y respectively.

In 3D I think I'm getting the angle correctly and thus x & y using cosine and sine, but I'm not sure what to do for z. Can anyone please advise on how this is derived? Thank you!

def GetAngle(line):
    fCrossX = line.p1.y * line.p2.z - line.p1.z * line.p2.y
    fCrossY = line.p1.z * line.p2.x - line.p1.x * line.p2.z
    fCrossZ = line.p1.x * line.p2.y - line.p1.y * line.p2.x
    fCross = math.sqrt(fCrossX * fCrossX +
        fCrossY * fCrossY + fCrossZ * fCrossZ)
    fDot = line.p1.x * line.p2.x + line.p1.y * line.p2.y + line.p1.z + line.p2.z
    return math.atan2(fCross, fDot)

v1 = Vector(100,0,0)
v2 = Vector(500,0,0)
line = Line(v1,v2)
angle = GetAngle(line)
sin = math.sin(angle)
cos = math.cos(angle)
points = list()
for i in range(int(line.length)):
    x = line.p1.x+(cos*i)
    y = line.p1.y+(sin*i)
    # what do I do for z???
    pt = Vector(x,y)

You shouldn’t need to use any trigonometry here at all. If you get the vector from v1 to v2 and divide it by the number of points you want along the line, each subsequent point is v1 + (that vector) × (the index of the point). Works in any number of dimensions, faster than the trigonometric approach.

v1 = Vector(100, 200, 300)
v2 = Vector(500, 400, 300)
steps = 25 # or however many subdivisions you want: int(length(Line(v1, v2))) if you want an equivalent to the original
stepAmount = Vector((v2.x - v1.x) / steps, (v2.y - v1.y) / steps, (v2.z - v1.z) / steps)
points = list()
for i in range(steps + 1)
    x = v1.x + stepAmount.x * i
    y = v1.y + stepAmount.y * i
    z = v1.z + stepAmount.z * i
    points.append(Vector(x, y, z))
  • $\begingroup$ That worked! Brilliant, thank you Noah :-D $\endgroup$ Feb 5 at 1:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.