Avoid Crossing Of Geometries
I would like to work with this code:  Unfortunately, the geometries sometimes cross. How is it possible to avoid that? Would be very thankful for help!
Solution 1:
Calculate the center of the bounding box of the points and sort the points by the angle of the vector from the center to the point:
let ax = vertices.map(v => v.x);
let ay = vertices.map(v => v.y);
let cx = (Math.min(...ax) + Math.max(...ax)) / 2;
let cy = (Math.min(...ay) + Math.max(...ay)) / 2;
vertices.sort((a, b) => { 
    let v1 = p5.Vector.sub(a, createVector(cx, cy));
    let v2 = p5.Vector.sub(b, createVector(cx, cy));
    returnMath.atan2(v1.y, v1.x) - Math.atan2(v2.y, v2.x); 
});
In the following example, the lines that form the center point to the vertices are drawn to visualize the algorithm:
let vertices = [];
let cx, cy
functionsetup() {
    createCanvas(windowWidth, windowHeight);
    let numberOfVertices = random(3, 11); //pick the number of pointsfor (let i = 0; i < numberOfVertices; i++) {
        vertices.push(createVector(random(width), random(height))); //add a point to the list of points
    }
    
    let ax = vertices.map(v => v.x);
    let ay = vertices.map(v => v.y);
    cx = (Math.min(...ax) + Math.max(...ax)) / 2;
    cy = (Math.min(...ay) + Math.max(...ay)) / 2;
    vertices.sort((a, b) => { 
        let v1 = p5.Vector.sub(a, createVector(cx, cy));
        let v2 = p5.Vector.sub(b, createVector(cx, cy));
        returnMath.atan2(v1.y, v1.x) - Math.atan2(v2.y, v2.x); 
    });
}
functiondraw() {
    background(220);
    fill(255, 0, 0);
    noStroke();
    beginShape();
    for (let i = 0; i < vertices.length; i++) {
        vertex(vertices[i].x, vertices[i].y);//place each vertex
    }
    endShape();
    stroke(255, 255, 255);
    strokeWeight(3)
    for (let i = 0; i < vertices.length; i++) {
        line(cx, cy, vertices[i].x, vertices[i].y);
    }
}<scriptsrc="https://cdn.jsdelivr.net/npm/p5@1.3.1/lib/p5.js"></script>
Post a Comment for "Avoid Crossing Of Geometries"