简体   繁体   English

如何使数组与 intersects() function 中的 object 交互?

[英]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控制台说 apple.intersects 不是 function,由于某种原因,我不能将苹果阵列与 object 一起使用

the console says that apple.intersects is not a function控制台说 apple.intersects 不是 function

Of course, because intersects would have to be a method of the class Boks .当然,因为intersects必须是 class Boks的一种方法。 You've to move the declaration in the scope of Boks您必须在Boks的 scope 中移动声明

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.该方法必须在 class Boks的实例上调用,而不是在数组上调用。 eg:例如:

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: Javascript算法版本:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM