Mr.Ulis
Mr.Ulis

Reputation: 157

how can i make an array interact with a object in a intersects() function?

snake = new Boks(300,300,10,10)

let apple = [];
for(i = 0; i<5; i++){
    let x = random(20,560); 
    let y = random(20, 560)
    apple[i] = new Boks(x,y,10,10)
}

for(i = 0; i<apple.length; i++){ 
    eple[i].visEple();    //a example of how i called the apple object/array
}

if (apple.intersects(snake)){
    background(255,0,0)          //the intersects function
}

intersects(other){
    let di = dist(this.x,this.y,other.x,other.y)
    if (di < this.w) { //this.w is the radius of the apple
        return true;
    } else {
        return false;
    }
}

the console says that apple.intersects is not a function, for some reason i cant use the apple array with the object

Upvotes: 1

Views: 513

Answers (1)

Rabbid76
Rabbid76

Reputation: 210909

the console says that apple.intersects is not a function

Of course, because intersects would have to be a method of the class Boks. You've to move the declaration in the scope of Boks

class Bocks {

    constructor(x, y, w, h) {

        // [...]
    } 

    intersects (other) {
        let di = dist(this.x,this.y,other.x,other.y)
        return di < this.w;
    }
}

The method has to be called on an instance of the class Boks, rather than on the array. e.g.:

for (i = 0; i<apple.length; i++){ 
    if (apple[i].intersect(snake)) {

        // [...]
    }
}

But note, your intersection test, just test if a point is inside an circular area.
To calculate the intersection of a rectangle and circle see Circle-Rectangle collision detection (intersection).
Javascript version of the algorithm:

function intersectCircleRect(circle_x, circle_y, radius, rect_x, rect_y, rect_w, rect_h) {

    // calculate the center of the rectangle
    let rect_cpt_x = rect_x + rect_w/2;
    let rect_cpt_y = rect_y + rect_h/2;

    // calculate the distance of the rectangle center to the circle center
    let dx = abs(circle_x - rect_cpt_x);
    let dy = abs(circle_y - rect_cpt_y);

    // if either dx or dy is greater than the sum of radius half side length, then there is no intersection
    if (dx > rect_w/2 + radius)
        return false;
    if (dy > rect_h/2 + radius)
        return false;

    // if center of circle is in rectangle then there is an intersection
    if (dx <= rect_w/2)
        return true;
    if (dy <= rect_h/2)

    // evaluate intersection by Euclidean distance
    let ratio = min(rect_w/2 / dx), rect_h/2 / dy);
    t_dx = dx - dx * ratio;
    t_dy = dy - dy * ratio;
    d_sq = t_dx*t_dx + t_dy*t_dy;
    return d_sq < radius*radius;
}

Upvotes: 1

Related Questions