我之前问过一个关于如何让AI在我的Agar.io克隆游戏中追逐食物的的问题,后来我自己解决了,但现在我无法让它追逐离它最近的食物。我尝试通过创建两个数组来存储食物细胞与电脑之间的(x, y)距离(如这个fiddle所示),但AI仍然会追逐更远的食物。以下是我代码的相关部分:
返回必要的值:
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’是返回这些值的函数)
如何让AI尝试吃离它最近的食物,而不是任意一个细胞?
回答:
对它们进行排序:
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
已经设置,如您的问题中所述。
编辑:
您不需要使用sqrt。这很耗费资源,而且没有必要。试试这个替代方案:
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);})