在半径范围内拾取食物对象

Picking up food object in radius

我正在为学校项目制作遗传算法。目前我正在为 "dot" 移动和拾取食物的物体打下基础。我写了一些我认为应该能够做到这一点的代码,经过反复试验,我想到了这个。 (它可能不是最干净的代码,我也很想听听一些关于它的提示)。代码的唯一问题是对象不只是拾取 1 种食物,而是多种食物,我不知道为什么。

I've tried putting the food objects index in a seperate Array so I can later remove it from the food Array (when I know the index to remove >> 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) {
                target = inRange[i];
                targetIndex = indexArray[i];
                closest = d;
            }
        }

        let targetpos = createVector(target.pos.x, target.pos.y); //fixed food removing from function (resetting position by using sub)
        let desired = targetpos.sub(this.pos);
        desired.normalize();
        desired.mult(this.maxspeed);
        let steeringForce = desired.sub(this.vel);
        this.applyForce(steeringForce);

        for (let i = 0; i < food.length; i++) {
            let d = dist(target.pos.x, target.pos.y, this.pos.x, this.pos.y);
            if (d < this.size) {
                console.log(targetIndex);
                this.food_eaten += 1;
                food.splice(targetIndex, 1);
            }
        } 
    }
}

使用此代码我没有收到任何错误消息,我使用 console.log 记录了 targetIndex。这导致多次获得相同的输出。

[...] the object does not just pick up 1 food but multiple [...]

当然有,因为在

for (let i = 0; i < food.length; i++) {
   let d = dist(target.pos.x, target.pos.y, this.pos.x, this.pos.y);
   if (d < this.size) {
       // [...]
   }
}

条件d < this.size不依赖于food[i],如果条件满足它接受数组中的每个食物。

只需跳过for循环,即可解决问题。请注意,您想要 "eat" 一种食物,因此验证 1 种食物是否在范围内就足够了。食物的索引已经被识别并存储在 targetIndex:

//for (let i = 0; i < food.length; i++) {

let d = dist(target.pos.x, target.pos.y, this.pos.x, this.pos.y);
if (d < this.size) {
    console.log(targetIndex);
    this.food_eaten += 1;
    food.splice(targetIndex, 1);
}

//}