javascript - 让AI追逐最近的食物

标签 javascript html canvas artificial-intelligence

前段时间我问了一个关于如何让人工智能在我的 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}...],以及 computerYcomputerX 已设置,如您的问题所示。

编辑:

你不需要开方。它很密集,而且不需要。试试这个:

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/

相关文章:

javascript - 该对象在数组中,但indexOf找不到dit

html - 背景图像高度和宽度在 IE11 上不起作用

javascript - javascript 项目和数组的问题(下雨)

javascript - RequireJS - 导出一组函数

javascript - Angular react 形式阵列

javascript - javascript中的curry函数是否使用闭包原则?

javascript - Jquery将php工作加载到div中但不加载到表单中

javascript - 当 div 处于事件状态时更改按钮背景图像

javascript - 为什么 Canvas 的实现速度比 Pixi.JS 快?

android - 动态绘制形状