We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello - I have a nested for loop that I am having trouble with.
The purpose of the loop is to look at the distance between instances of a class as they move around.
The loop removes the two instances of the class if they get close.
I am trying to figure out how to make it create a new instance of the class at the collision location, after it has killed off the two instances that collided.
The problem is - creating a new instance of the class changes the creature count which then changes the for loops and puts them out of bounds.
If anyone has any solutions to this problem then that would be great!
void collideCreatures() {
for (int i = 0; i < creatureCount; i++) {
TweetAgent b = agents.get(i);
for (int j = i+1; j < creatureCount; j++) {
TweetAgent g = agents.get(j);
float dx = b.location.dist(g.location);
if (dx < 5) {
createAgent(new PVector(b.location.x, b.location.y));
b.alive=false;
g.alive=false;
}
}
}
}
void createAgent(PVector _location) {
agents.add(new TweetAgent(_location));
creatureCount = creatureCount + 1;
}
Answers
in line 8 just store the positions in a separate arraylist and create them from here after the nested forloops
Things would be much easier if you postpone the add() once the double loop is over.
Or at least create some temporary List for the new arrivals.
Once loop is finished, addAll() them to the main List:
http://docs.Oracle.com/javase/8/docs/api/java/util/List.html#addAll-java.util.Collection-
Hi - I had a go at the first suggestion but with no luck, maybe I have done something wrong:
looks good so far
do you have
collisionLocations.clear()
before line 2 ?btw 1: you could maybe just keep b ? Depending on your class' constructor which we don't know
btw 2: also, when you clear up agents (removing all with alive==false using
agents.remove(i);
) you need to loop backwards throughagents
false
, just keep it! :>false
, the other staystrue
.Hi thanks for your replies - unfortunately the above code is beyond my current level so I don't understand it.
Maybe if I add more of my code it will make more sense what is happening and why the first solution was unsuccessful:
The first part is the main sketch (I have commented out all the parts that I think are irrelevant to the problem but have included the entire sketch so that it makes sense what I am doing ( I am aware the quality of this code could be improved but it serves its intended purpose at the moment).
This is the creature class (there is also a predator class but it isnt relevant to include it):
My example wasn't that big, and I dunno how to simplify it any further. :|
If you could pinpoint exactly what you don't get, I may be able to explain it better. :-/
I guess I've got 2 old online examples which are very similar to your last example: