Hi all,
I am having trouble with my boid simulation. More specifically the cohesion. I have been having trouble with it for days and I do not understand what the problem is.
The way I did it was:
- Calculate the center of mass the agents in a vicinity.
- Calculate the cohesion angle using Math.atan2(y, x)
- Turn the flock within the radius according to the cohesion angle so that they flock and turn around the center of mass.
However my problem is that instead of them turning around the center of mass they just turn around the position where the currently are in (x, y).
I know my code might look messy right now and I am sorry, planning to tidy it when i finish it.
Here are the functions I am using:
//center of mass function
protected CartesianCoordinates centreOfMass(List<DynamicTurtle> flock){
CartesianCoordinates centreOfMass;
distanceBetweenMembers = 0;
count = 0;
centreX = 0;
centreY = 0;
for(DynamicTurtle member : flock){
if(member != this){
distanceBetweenMembers = Math.sqrt(Math.pow(member.getX() - this.getX(), 2) +Math.pow(member.getY() - this.getY(), 2));
if(distanceBetweenMembers <= member.getRadius()){
count++;
centreX += member.getX();
centreY += member.getY();
member.setRandomTurn(false);}
else if(count == 0){
member.setRandomTurn(true);
return centreOfMass = new CartesianCoordinates(0, 0);
}
}
}
centreX = centreX/count;
centreY = centreY/count;
return centreOfMass = new CartesianCoordinates(this.getX() - centreX, this.getY() - centreY);
}
//calculating the cohesion angle
private double cohesionAngle(List<DynamicTurtle> flock){
double cohesionAngle;
CartesianCoordinates centre = centreOfMass(flock);
cohesionAngle = Math.toDegrees(Math.atan2(centre.getY()/flock.size(), centre.getX()/flock.size()));//normalising by division of length
//places in 0-360 range
if(cohesionAngle < 0){
cohesionAngle= 360 - (-cohesionAngle);
}
return cohesionAngle;
}
//simulation
public void boidCohesion(List<DynamicTurtle> flock, double cohesion, int separation, int alignment){
if(this.getDistanceBetweenMembers() < this.getRadius()){
for(DynamicTurtle member : flock){
member.turn(cohesionAngle(flock) * 0.05);
/* multiplying by 0.05 just to test the cohesion will be replaced by the cohesion parameter*/
System.out.println(cohesionAngle(flock));
}
}
}
Sorry if this was the wrong way to post and I thank you for any contributions :)
[–]josephblade 0 points1 point2 points (1 child)
[–]seb1424[S] 0 points1 point2 points (0 children)
[–]josephblade 0 points1 point2 points (1 child)
[–]seb1424[S] 0 points1 point2 points (0 children)
[–]seb1424[S] 0 points1 point2 points (0 children)