简体   繁体   中英

Calculating angle between a line and a point in 3D

I'm working on a problem in c++ where I need to determine the angle between a line represented as 2 points in 3d (etc, xyz coordinates) and a disconnected point. Here are some pictures that might be easier to understand.

This is in 2D to display it easier

So what I need help with is finding this angle

With angle

I've been searching for several hours to solve this now, and I suspect that I've just missed something obvious. But if anyone can help me with this I will be very greatful:)

You have 2 vectors, first related to line in 3D and other vector connecting end point of the line and a point in 3D.

To calculate angle theta between 2 vectors, you can take advantage of the fact that V1.V2 = |V1| x |V2| x consine(theta) V1.V2 = |V1| x |V2| x consine(theta)

Here is code snippet I copied from here , to calculate dot product.

#include<numeric>    

int main() { 
    double V1[] = {1, 2, 3}; // vector direction i.e. point P2 - point P1
    double V2[] = {4, 5, 6}; // vector direction i.e. point P3 - point P2

    std::cout << "The scalar product is: " 
              << std::inner_product(begin(V1), end(V1), begin(V2), 0.0);

    // TODO: Get theta

    return 0;
}

Once you have the dot product, divide it by magnitudes of 2 vectors and then take inverse consine to get theta.

Use the Law of Cosines :

gamma = acos((asq + bsq - csq) / 2 / sqrt(asq*bsq))

where asq and bsq are the squared distances between the vertex and the other two points, and csq is the squared distance between those two points.

(drawing from Wikipedia )

let say you have A(x 1 ,y 1 ,z 1 ) B(x 2 ,y 2 ,z 2 ) C(x 3 ,y 3 ,z 3 ) and the common point is B. So the equation of the line AB becomes : (x 1 -x 2 )i + (y 1 -y 2 )j + (z 1 -z 2 )k and that for BC it is : (x 2 -x 3 )i + (y 2 -y 3 )j + (z 2 -z 3 )k

Cos theta = (AB.BC)/(|AB|*|BC|)

Here is the code

#include<iostream>
#include<math.h>
#define PI 3.14159265
using namespace std; 
int main()
{
    int x1,x2,x3,y1,y2,y3,z1,z2,z3;
    cout<<"for the first\n";
    cin>>x1>>y1>>z1;
    cout<<"\nfor the second\n";
    cin>>x2>>y2>>z2;
    cout<<"\nfor the third\n";
    cin>>x3>>y3>>z3;
    float dot_product = (x1-x2)*(x2-x3) + (y1-y2)*(y2-y3)+ (z1-z2)*(z2-z3);
    float mod_denom1 = sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) + (z1-z2)*(z1-z2));
    float mod_denom2 = sqrt((x2-x3)*(x2-x3) + (y2-y3)*(y2-y3) + (z2-z3)*(z2-z3));
    float cosnum = (dot_product/((mod_denom1)*(mod_denom2)));
    float cos = acos(cosnum)*180/PI;
    cout<< cos;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM