Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
Why is my line intersection code not detecting the closest boundaries for following boundaries?

I'm trying to make a raycasting algorithm using p5.js (not very efficiently) and have almost all of the collision set up. I cast a ray towards the edge of every boundary (I have yet to code the ray that goes right past the boundary edge), and that works perfectly. My only problem then is that the rays obviously sometimes go through other boundaries. So, I made a for loop that goes through every Boundary and casts a ray at the same angle it was before. If there is an intersection, I return the magnitude of the ray. If not, I return Infinity. Next, I find the index of the minimum value in the array, which all seems to work. This means that whatever the index of the minimum value is is the index of the boundary I want to calculate an intersection with. The code for the function is as follows:

//a = ray position x, b = ray position y, c = ray position + ray direction x, d = ray position + ray direction y
//the array bounds is array of Bound objects
//intersect() calculates if a ray and a line segment intersect and if so returns a vector with intersection point, otherwise returns vector of 0, 0
function findShortest(a, b, c, d) {
    shortestPossibilities = [];
    for(var i = 0; i < bounds.length; i ++) {
        if(intersect(a, b, c, d, bounds[i].x1, bounds[i].y1, bounds[i].x2, bounds[i].y2).mag() !== 0) {
            //add magnitude of intersection
            sPoss.push(intersect(a, b, c, d, bounds[i].x1, bounds[i].y1, bounds[i].x2, bounds[i].y2).mag());
        } else {
            //impossible to be smallest
            sPoss.push(Infinity);
        }
    }
    //find smallest value
    var minVal = Math.min(...sPoss);
    var indexOfVal = sPoss.indexOf(minVal);
    return indexOfVal;
}

However, this doesn't work. I tried to see why it wasn't working by assigning each boundary a new color ([0] = white, 1 = gray, [2] = orange, [3] = yellow, [4] = green, [5] = cyan, [6] = blue, [7+] = purple.) It seems that finding the closest boundary only works if the closest boundary has a lower index than the original boundary the ray was pointing to, as seen: enter image description here

Does anyone know what I did wrong?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!