Guye Incognito
Guye Incognito

Reputation: 2844

Determine the distance of a Vector 3 along another Vector 3

I have 2 3D vectors. (objects with X, Y and Z float values)

In my diagram below, I would like to determine the length of the green line. This is the distance along Vector 1 that Vector 2 is. Or, the distance from the origin to the end of a line on Vector 1 which is at 90' to Vector 1 and passes thorough the point at the end of Vector 2.

enter image description here

I am doing this in Unity3D so I have access to quite a few helper methods that enable me to get the length of a Vector3 and so on very easily.

Upvotes: 2

Views: 1992

Answers (3)

Lutz Lehmann
Lutz Lehmann

Reputation: 25992

The length is obviously

norm(v2)*cos(angle(v1,v2))

and since

cos(angle(v1,v2))=abs(dot(v1,v2))/norm(v1)/norm(v2)

the final formula is

abs(dot(v1,v2))/norm(v1)

One could also say that

e1 = v1/norm(v1)

is the unit vector in the direction of v1, and that the green vector is

dot(e1,v2)*e1

resulting in the same length formula.

Upvotes: 2

MBo
MBo

Reputation: 80187

This is projection of Vector2 onto Vector1 direction. The simplest way (I think) to find it - using scalar product

D = |V2| * DotProduct(V2, V1) / (|V2| * |V1|) = DotProduct(V2, V1) / |V1|

where |V1| is the length of V1 vector

Upvotes: 2

Powderek
Powderek

Reputation: 251

Im not sure but I think this is what you wanted

Vector3 distance = Vector3.Lerp(Vector3.zero, vector_1, vector_2.sqrMagnitude / vector_1.sqrMagnitude);

http://docs.unity3d.com/ScriptReference/Vector3-sqrMagnitude.html

http://docs.unity3d.com/ScriptReference/Vector3.Lerp.html

Upvotes: 0

Related Questions