前段时间我问了一个关于如何让人工智能在我的 Agar.io 克隆中追逐食物的问题,我最终自己弄清楚了,但现在我不知道如何让它追逐最近的食物到它。我尝试创建两个数组,其中食物细胞和其中的计算机之间的距离为 (x, y)(如 this fiddle 中所示,但人工智能仍然会追踪更远的数组。以下是我的代码的相关部分:
返回必要的值:
var x = [];
var y = [];
x.push(cell.x - computerX);
y.push(cell.y - computerY);
return [Math.min.apply(null, x), Math.min.apply(null, y)];
应用它们:
this.xxx = xy()[0];
this.yyy = xy()[1];
this.dist2 = Math.sqrt(this.xxx * this.xxx + this.yyy * this.yyy);
this.speedX = (this.xxx / this.dist2) * this.speed.x;
this.speedY = (this.yyy / this.dist2) * this.speed.y;
computerX += 28 * this.speedX / computerRadius;
computerY += 28 * this.speedY / computerRadius;
(注意:“xy”是返回值的函数)
我如何让人工智能尝试吃离它最近的食物而不是任何细胞?
最佳答案
对它们进行排序:
food.sort(function(cell1, cell2){
var a1 = cell1.x - computerX, b1 = cell1.y - computerY,
a2 = cell2.x - computerX, b2 = cell2.y - computerY,
cell1Dist = Math.sqrt(a1*a1 + b1*b1),
cell2Dist = Math.sqrt(a2*a2 + b2*b2);
return (cell1Dist > cell2Dist)? 1 : ((cell1Dist < cell2Dist)? -1 : 0)
})
假设 food = [{x: 4, y: 3}, {x: 7, y: 9}...]
,以及 computerY
和 computerX
已设置,如您的问题所示。
编辑:
你不需要开方。它很密集,而且不需要。试试这个:
calcDist = function(cell){
var a = cell.x - computer.x, b = cell.y - computer.y;
return a*a + b*b;
}
food.sort(function(cell, cell2){
return calcDist(cell) - calcDist(cell2);
})
关于javascript - 让AI追逐最近的食物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33965918/