A question about how to remove sprites from a vector

In my game, I use a schedule to add a sprite into a vector every 0.5s, and I use a thread to check if the position Y of these sprites are less than 0, I will remove them. The code I wrote is here:

void Main::threadCheckPositionY()
{
	while (true)
	{
		std::this_thread::sleep_for(std::chrono::microseconds(10));
		Sprite* obj=nullptr;
		for (auto stage : stages)
		{
			if (stage->getPositionY() < 0){
				obj = stage;
			}
			if (stage->getPositionY() + stage->getContentSize().height / 2 <= ball->getPositionY() - ball->getContentSize().height / 2)
				stage->getPhysicsBody()->setCategoryBitmask(0x0005);
		}
		if (obj != nullptr)
		{
			stages.eraseObject(obj);
			removeChild(obj);
		}
	}
}

However, I have two questions. First, do I need to do both of “stages.eraseObject(obj);” and “removeChild(obj);” for removing the sprite? or just use one of them? Second, when this code run, it always stop because of this error “iterator not incrementable” do any one know why is it?

First, why do you use a thread, instead a scheduler or a timer? The while loop eats up a lot of CPU time, which is absolutely not necessary.

You need to remove the obj from your stages container and the layer, as the reference count is two, not one,

The iterator error message is thrown, because your container does not support iterators, which can be incremented. Use a container, which supports them or use iterators directly, instead of the new C++11 range based loops.

@iQD Thank you for answering me. I use thread because in my last game I did all works with scheduler at first, but it made the game not smooth, the fps dropped often. Then, I tried to use some threads instead of schedulers to do a part of works, the game’s fps was better than before. I don’t know if it’s the best way to solve the fps drops problem, but it does work. That’s why I try to do same thing again.

In general if you’re using cocos2d::Vector<>:

  • You should eraseObject for every associated pushObject. You can also .clear() the entire Vector instead. But the vector will retain when pushed and release when erased.

  • You should removeChild(obj) for every addChild(). This part is for releasing and removing it from it’s parent who has retained it when added. Note that replacing a scene or removing the parent will remove and release all of its children.