alexbol99 / flatten-js

Javascript library for 2d geometry
MIT License
535 stars 56 forks source link

ray and segment intersect #151

Closed itfanr closed 10 months ago

itfanr commented 10 months ago

image Given a line segment and a ray with the start point and direction vector, calculate the intersection point. The code is as follows:


    let s = segment(point(636, 281.5), point(336, 281.5));

    let r = ray(point(486, 271), vector(71.147335, 70.2713));

    let ip = s.intersect(r);

    if (ip.length > 0) {
      console.log(ip[0].x, ip[0].y);
    }

The expectation of this code is to output the intersection point. But I cannot get it.

Can someone help me?

alexbol99 commented 10 months ago

Hi, @itfanr According to my sketch the ray directed not as you expected: image See https://observablehq.com/@alexbol99/ray-and-segment-intersect-151 This is definitely wrong, ray supposed to be directed to the right of the normal vector. I will check this. You may help me to check if you want

itfanr commented 10 months ago

I am a new js user. I will try to fix it. Thank you for your attention to this issue.

alexbol99 commented 10 months ago

@itfanr , Actually there is no mistake. Simply this library makes an assumption that "y"-axis goes upwards, like in math. In the image "y"-axis usually goes downwards, which makes it look like in mirror. In order to get result that you expected, you have to invert vector to be vector(-71.147335, -70.2713)):

image
itfanr commented 10 months ago

@alexbol99 Thank you. I think I need to check the coordinate system and add some transform.

itfanr commented 10 months ago
    let s = segment(point(336, -281.5), point(636, -281.5));

    let r = ray(point(486, -271), vector(71.147335, -70.2713));

    let ip = s.intersect(r);

    if (ip.length > 0) {
      console.log(ip[0].x, ip[0].y);
    }

I calculated in third quadrant and got the interesct intersection (475.6292861847882, -281.5)