Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在半径范围内拾取食物对象_Javascript_Processing_P5.js - Fatal编程技术网

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

Javascript 在半径范围内拾取食物对象,javascript,processing,p5.js,Javascript,Processing,P5.js,我正在为一个学校项目做一个遗传算法。目前,我正在为“点”物体移动和拾取食物奠定基础。我写了一些代码,我认为应该能够做到这一点,经过一些尝试和错误,我想出了这个。(这可能不是最干净的代码,我也希望听到一些关于这方面的提示)。代码的唯一问题是,对象不仅拾取1种食物,而且拾取多种食物,我不知道为什么 我尝试将食物对象索引放在一个单独的数组中,以便以后可以将其从食物数组中删除(当我知道要删除的索引>targetIndex) checkForTarget(){ 设inRange=newarray(); 设

我正在为一个学校项目做一个遗传算法。目前,我正在为“点”物体移动和拾取食物奠定基础。我写了一些代码,我认为应该能够做到这一点,经过一些尝试和错误,我想出了这个。(这可能不是最干净的代码,我也希望听到一些关于这方面的提示)。代码的唯一问题是,对象不仅拾取1种食物,而且拾取多种食物,我不知道为什么

我尝试将食物对象索引放在一个单独的数组中,以便以后可以将其从食物数组中删除(当我知道要删除的索引>
targetIndex

checkForTarget(){
设inRange=newarray();
设indexArray=新数组();
for(设i=0;i
我没有收到此代码的任何错误消息,我使用console.log记录
targetIndex
。这会导致多次获得相同的输出

[…]对象不仅拾取一种食物,还拾取多个[…]

当然有,因为

for(让i=0;i
条件
d
不依赖于
食物[i]
,如果条件满足,它会接受数组中的每种食物

只需跳过
for
循环即可解决问题。注意,您想要“吃”一种食物,因此验证一种食物是否在范围内就足够了。食品索引已识别并存储在
targetIndex

//for(设i=0;i
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);
            }
        } 
    }
}