Reputation: 630
I have instantiated two arrays, one for player projectiles, and another for enemies.
Each entity has a collision circle. When two entities collide, I'd like to remove both objects from the arrays they're in, but I'm having some trouble with this.
One solution I've tried is to give each entity a value, then they can be referenced later when removing them.
I'd get the values of the entities that collided, and remove it from the arrays, then decrement the value of enemies ahead of the enemies; this was in order to correct the values with their new index. However, after a collision it wouldn't actually decrement, so an ArrayIndexOutOfBoundsException
exception would occur instead.
private void didCollisionOccur() {
for (Alien alien : aliens) {
for (PlayerShot playerShot : playerShots) {
if (Intersector.overlaps(alien.getCircle(), playerShot.getCircle())) {
alien = aliens.removeIndex(0);
playerShot = playerShots.removeIndex(0);
}
}
}
}
I'm currently using removeIndex(0)
as a "workaround". This isn't actually what I want though as it will always remove the first element of the array, not the one that had the collision.
The following is the method I was hoping to be my solution.
private void didCollisionOccur() {
for (Alien alien : aliens) {
for (PlayerShot playerShot : playerShots) {
if(Intersector.overlaps(alien.getCircle(), playerShot.getCircle())) {
getCountHolder = alien.getCount();
alien = aliens.removeIndex(alien.getCount());
playerShot = playerShots.removeIndex(0);
}
}
}
for(Alien alien : aliens) {
if (alien.getCount() >= getCountHolder)
alien.takeFromCount(1);
}
}
The following is in Alien.java
:
public void takeFromCount(int value) {
count -= value;
}
public int getCount() {
return count;
}
Upvotes: 0
Views: 1354
Reputation: 26
Have you tried the method removeValue()?
I guess with that you can solve your problem.
private void didCollisionOccur()
{
for(Alien alien : aliens)
{
for(PlayerShot playerShot : playerShots)
{
if(Intersector.overlaps(alien.getCircle(), playerShot.getCircle()))
{
aliens.removeValue(alien,true);
playerShots.removeValue(playerShot,true);
}
}
}
}
Now it can be that java cause a current modification exception. If this is the case you need to reference both objects outside the loop and remove it after.
private void didCollisionOccur()
{
Alien tmpAlien = null;
PlayerShot tmpPlayerShot = null;
for(Alien alien : aliens)
{
for(PlayerShot playerShot : playerShots)
{
if(Intersector.overlaps(alien.getCircle(), playerShot.getCircle()))
{
tmpAlien = alien;
tmpPlayerShot = playerShot;
}
}
}
if(tmpAlien != null && tmpPlayerShot != null)
{
aliens.removeValue(tmpAlien,true);
playerShots.removeValue(tmpPlayerShot,true);
}
}
Upvotes: 1