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;
}
}
控制台说apple.intersects不是一个函数,由于某种原因我无法将applet数组与该对象一起使用
最佳答案
控制台说apple.intersects不是一个函数
当然,因为intersects
必须是Boks
类的方法。您必须将声明移至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;
}
}
该方法必须在类
Boks
的实例上调用,而不是在数组上调用。例如。:for (i = 0; i<apple.length; i++){
if (apple[i].intersect(snake)) {
// [...]
}
}
但是请注意,您的交集测试只是测试一个点是否在圆形区域内。
要计算矩形和圆形的交点,请参见Circle-Rectangle collision detection (intersection)。
该算法的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
t_dx = dx - rect_w/2;
t_dy = dy - rect_h/2;
d_sq = t_dx*t_dx + t_dy*t_dy;
return d_sq < radius*radius;
}