我正在为学校项目制定遗传算法。目前,我正在为移动并拾取食物的“点”对象建立基础。我写了一些我认为应该可以做到的代码,经过一番尝试和错误之后,我想到了这个。(这可能不是最干净的代码,我也希望听到一些有关此的提示)。该代码的唯一问题是该对象不仅会拾取1种食物,而且还会拾取多种食物,我不知道为什么。
我尝试将食物对象索引放在单独的数组中,以便稍后可以从食物数组中将其删除(当我知道要删除>>的索引时
targetIndex)
checkForTarget() {
let inRange = new Array();
let indexArray = new Array();
for (let i = 0; i < food.length; i++) {
let d = dist(food[i].pos.x, food[i].pos.y, this.pos.x, this.pos.y);
if (d < this.sense) {
inRange.push(food[i]);
indexArray.push(i);
}
}
if (!inRange.length == 0) {
let closest = this.sense; // this.sense = radius
let target, targetIndex;
for (let i = 0; i < inRange.length; i++) {
let d = dist(inRange[i].pos.x, inRange[i].pos.y, this.pos.x, this.pos.y);
if (d < closest) { …Run Code Online (Sandbox Code Playgroud)