Search code examples
linedistanceangledotpoints

Need to check if point X is in any distance from a line made between 2 dots


I am using Sourcepawn, can also understand java ,but I need just a tip, idea to work on

Image - 2 red dots are end points of the beam. Beam can be in any angles (X,Y). I need to focus on green dot, check the closest distance between orange line (I don't have any points more, just 2 ends) and green dot.

Any tips appreciated, thanks!


Solution

  • Sketch: 3 points Given that you want to know the vector d with defined points p1, p2 and p3 you could do the following (vector variables are underlined):




    Or, in a more code friendly notation (I am using JavaScript here) we represent vectors as arrays with x- and y-values:

    const fromP1=(p,i)=>p-p1[i],   // subtract vector p1 from current vector
             dot=(a,b)=>a.reduce((v,p,i)=>v+p*b[i],0); // scalar product
    // these are just arbitrary sample point values:
    const p1=[1,5,0], p2=[6,2.5,0], p3=[2,2,0];
    
    const a=p2.map(fromP1),         // vector from P1 to P2
      b=p3.map(fromP1),             // vector from P1 to P3
     fa=dot(a,b)/dot(a,a),          // scalar factor for vector a
      c=a.map(p=>p*fa),             // scale vector a by fa
      d=b.map((p,i)=>p-c[i]);       // vector d = vector b - vector c
      
      console.log("vector c:",c);
      console.log("vector d:",d)

    As a little side note: This method works just as well for 3 (or even more!) dimensions. Simply add further components (=coordinate values) to (all of) the vector arrays. The vector functions will automatically work with all defined dimensions.

    enter image description here

    If you only want to know the scalar value of the minimum distance then things get a littlie easier:

    const fromP1=(p,i)=>p-p1[i],    // subtract vector p1 from current vector
             dot=(a,b)=>a.reduce((v,p,i)=>v+p*b[i],0); // scalar product
                                    // sample point values (3D):
    const p1=[1,5,0], p2=[6,2.5,0], p3=[2,2,0];
    
    const a=p2.map(fromP1),         // vector from P1 to P2
          b=p3.map(fromP1);         // vector from P1 to P3
    
    const ab=dot(a,b);
    
    console.log("distance:",Math.sqrt(dot(b,b) - ab*ab/dot(a,a)) );