[Closed] Vector projection onto another vector
Given two splines, I’ve managed to calculate the length of the vector projection of a onto b (see attached image).
The result is represented by the green square.
The question is: how do I calculate the same result but ALONG the vector b?
Here’s my code
–get the vectors
firstPoint1 = getKnotPoint selection[1] 1 1
secondPoint1 = getKnotPoint selection[1] 1 2
newVec1 = secondPoint1 – firstPoint1
normalizedVector1 = normalize newVec1
firstPoint2 = getKnotPoint selection[2] 1 1
secondPoint2 = getKnotPoint selection[2] 1 2
newVec2 = secondPoint2 – firstPoint2
normalizedVector2 = normalize newVec2
–get the angle between the splines
result = acos (dot normalizedVector1 normalizedVector2)
–get the length of the projection
result2 = (length newVec1)*(cos result)
b = box width:2 length:2 height:2
b.position = [result2,0,0]
I’ve found the solution myself: I needed to multiply that result by the normalized b vector
/******************** MATH ******************/
fn projectPoint2Vec a b p =
(
t = dot (normalize (b - a)) (normalize (p - a))
c += normalize (b - a) * length (p - a) * t
)
/**************** TEST SCENE *************/
delete objects
gc()
ab = splineshape name:"AB" wirecolor:orange
addnewspline ab
addKnot ab 1 #corner #line [0,0,0]
addKnot ab 1 #corner #line [100,0,0]
updateshape ab
cd = splineshape name:"CD" wirecolor:green
addnewspline cd
addKnot cd 1 #corner #line [0,0,0]
addKnot cd 1 #corner #line [150,0,-50]
updateshape cd
/*************** CALC ********************/
a = getknotpoint ab 1 1
b = getknotpoint ab 1 2
c = getknotpoint cd 1 1
d = getknotpoint cd 1 2
pt = projectPoint2Vec c d b
pr = point name:"PROJ" pos:pt wirecolor:red cross:on