I'm trying to detect which sprite was touched in an array of sprites and when it is touched to run an animation at the sprite which was touched. I have all the sprites placed in the map already but when the user touches any other sprite except for the first one the animation doesn't run. I'm using cocos2dx 3.5. Any help is appreciated thank you.
this is my onTouchesEnded
void BattleScreen::onTouchesEnded(const std::vector<cocos2d::Touch *> &touches, cocos2d::Event *event)
{
for (auto touch : touches)
{
auto tapped = touch->getLocationInView();
for (int i = 0; i < defenseSpots.size(); i++) {
if(defenseSpot[i]->getBoundingBox().containsPoint(tapped))
{
sealAnimationSprite = Sprite::create("sealanimation5.png");
sealAnimationSprite->setPosition(Point(defenseSpot[i]->getPosition().x, defenseSpot[i]->getPosition().y));
this->addChild(sealAnimationSprite,20);
// now lets create animation frames
Vector<SpriteFrame*> sealAnimationFrames;
sealAnimationFrames.reserve(5);
sealAnimationFrames.pushBack(SpriteFrame::create("sealanimation5.png", Rect(0,0,100,100)));
sealAnimationFrames.pushBack(SpriteFrame::create("sealanimation4.png", Rect(0,0,100,100)));
sealAnimationFrames.pushBack(SpriteFrame::create("sealanimation3.png", Rect(0,0,100,100)));
sealAnimationFrames.pushBack(SpriteFrame::create("sealanimation2.png", Rect(0,0,100,100)));
sealAnimationFrames.pushBack(SpriteFrame::create("sealanimation.png", Rect(0,0,100,100)));
// create the animation out of the frames
Animation* sealAnimation = Animation::createWithSpriteFrames(sealAnimationFrames, 0.01f);
animateSeal = Animate::create(sealAnimation);
// run it and repeat it forever
sealAnimationSprite->runAction((animateSeal));
}
}
}
}
and here is my method where i create the sprites and place them
void BattleScreen::createDefenseSpots()
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
for (int i = 0; i < 4;i++)
{
defenseSpot[i] = Sprite::create("placement.png");
if(i == 0)
defenseSpot[i]->setPosition(Point(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
if (i == 1)
defenseSpot[i]->setPosition(Point(visibleSize.width / 1.4 + origin.x, visibleSize.height / 3+ origin.y));
if (i == 2)
defenseSpot[i]->setPosition(Point(visibleSize.width / 3.5 + origin.x, visibleSize.height / 1.5 + origin.y));
if (i == 3)
defenseSpot[i]->setPosition(Point(visibleSize.width / 2.5 + origin.x, visibleSize.height / 4+ origin.y));
this->addChild(defenseSpot[i]);
defenseSpots.push_back(defenseSpot[i]);
}
}
Everything adds to the scene correctly but the only sprite the will run the animation is the first one. Im guessing the loop isn't executing correctly but I'm not sure how to fix it?
I've also tried looping through like this
for(int i = 0;i < 4; i++){
...
}