Remove object from Array without knowing index

Hey guys. I’m working on the collision detection for my pacman game. I’ve got the pills to load and show on the map, however, in my main class, i’m trying to make it so when the pacman touches one of the pills it removes it from the array. I don’t know the index of the pill it hit, so I can’t just do pillList.removeIndex(index)…I’ve tried a bunch of things and been searching to no avail. Any ideas?


public void update() {
		//float deltaTime = Gdx.graphics.getDeltaTime();
		
		for (Pills tempPill :  map.getPillList()) {
			tempPill.checkCollision(player.getRect());
			if (tempPill.GetVisible() == false) {
				
			}
		}
		
		keyInput();
		
		player.move(map);
		
	}

The pillList holds all of the pill objects. When the player rectangle overlaps the pill rectangle, it sets the isVisible boolean of the pill object to false…Now i’m trying to iterate through the pill list, and if the isVisible is equal to false, I want to remove the pill from the list.

I can do it like this, but it seems like this is an outdated way to do it…


for (int p = 0; p < map.getPillList().size;p++) {
			map.getPillList().get(p).checkCollision(player.getRect());
			if (map.getPillList().get(p).GetVisible() == false) {
				map.getPillList().removeIndex(p);
			}
		}

You could generate an ID for each pill, then when you hit a pill, you collect its ID, iterate through the list, and match it to get the index.
You could also use a HashMap that links each pill to an ID number, then you could just call map.remove().

That’s not a bad idea. I haven’t used HashMaps yet, so now might be a good time to learn how…I think for now, I may stick with the latter method I posted, as it is working. I’ll eventually change it, as this is really just a learning project.

Compare the references and loop the list. Linear search is simple and fast.

I took a different approach to my PacMan clone. The map is a grid of values which can represent:

  • a wall
  • corridor without pill
  • corridor with pill

If the player encroaches a certain distance into a corridor cell that has a pill, then the pill is swallowed and cell reverts to “corridor without pill”.

This sort of thing won’t work as well when you have a whole range of different static things that can occupy a cell at the same time, but PacMan is not such a game. You have pills, big pills and sometimes fruit.

The 2nd way is not outdated, it has the advantage of not creating an iterator each time.
But it is not working correctly cause the index is not handled properly and thus checks are skipped (after removal).
Instead of " == false" rather use “if (!temoPill.getVisible())”