I'm making a Genetic Algorithm for a school project. Currently I'm building the foundation for the "dot" objects that move around and pick up food. I wrote some code that I thought should be able to do that and after some trial and error I came up with this. ( It's probably not the cleanest code and I would love to hear some tips about that as well). The only problem with the code is that the object does not just pick up 1 food but multiple and I don't know why.
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);
}
}
}
}
I don't get any error messages with this code, I used console.log to log the targetIndex
. Which results in getting the same output multiple times.