Calling touches[i]->getLocation() causes an error but casting to a variable works. I'm confused!

Hi there, all!

I’m working on an Android game at the moment (using Cocos2D, C++ and debugging on Android and Windows) and I’m currently implementing some touch controls to it. I have come across an interesting issue and was hoping somebody could shed some light on it for me. It has something to do with storing the position of a touch in a variable compared to getting the position of the touch itself.

Here’s the code:

bool GameScene::initTouchListener()
{
	if (!Layer::init())
	{
		return false;
	}

	label = Label::createWithSystemFont("", "Arial", 42);
	label->setAnchorPoint(Vec2(0.5f, 0.5f));
	label->setAlignment(cocos2d::TextHAlignment::CENTER, cocos2d::TextVAlignment::CENTER);
	label->setVisible(false);
	this->addChild(label);

	auto eventListener = EventListenerTouchAllAtOnce::create();

	eventListener->onTouchesBegan = [=](const std::vector<Touch*>&touches, Event* event)
	{
		for (int i = 0; i < touches.size(); ++i) {
			label->setPosition(touches[i]->getLocation());
			label->setVisible(true);
			label->setString("Touched");

			Vec2 mousePos = label->getPosition();
			auto draw = cocos2d::DrawNode::create();
			draw->drawLine(ark->getPosition(), touches[i]->getLocation(), cocos2d::Color4F::ORANGE);
			addChild(draw);

			for (int i = 0;i < alienShips.size();i++)
			{
				auto draw = cocos2d::DrawNode::create();
				draw->drawLine(alienShips[i]->getPosition(), mousePos, cocos2d::Color4F::YELLOW);
				addChild(draw);
			}
		}
	};

	_eventDispatcher->addEventListenerWithSceneGraphPriority(eventListener, this);

	return true;
}

The variable “mousePos” where I am drawing the line (in the for loop for alienShips) is where the issue occurs. If I use “mousePos” or “label->getPosition()” then it works fine; it draws the lines and no error messages appear. However, if I use “touches[i]->getLocation()” then the application calls an error that says “Vector subscript out of range.”

I can continue with development by casting the touch position to a variable and using the variable (as I am with “mousePos”), but I’m curious as to why I can’t call “touches[i]->getLocation()” instead.

Thanks in advance for anybody who is able to assist me with this!

Raspilicious

You’re using same variable name ‘i’ in the double for-loop.
That may cause a out-of-range error.

You are a genius!

I changed the i in the second for-loop to j and boom - no more errors.

Thank you very much! :smiley: <3