[SOLVED]If sprite in an array is touched

I have a 10 by 10 array of sprites and I want to check which one of them was touched and then remove it, but when I compile and run this code on android all i can do is click only one of these sprites and it disappears as it’s supposed to, but if i then click an other one my app just crashes. I also can click the sprites that are diagonally to the left down corner under the first sprite clicked without crashing the app. The code is below:

bool MineScene::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event) {
for(int i = 0; i <= 10; i++){
  for (int j = 0; j <= 10; j++) {
    if (tiles[i][j]->getBoundingBox().containsPoint(this->convertTouchToNodeSpace(touch))) {
        this->removeChild(tiles[i][j]);
     }
  }
}
return true;
}

Missing null checking of tiles[i][j] in the if statement:

bool MineScene::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event) {
for(int i = 0; i <= 10; i++){
  for (int j = 0; j <= 10; j++) {
    if (tiles[i][j] && tiles[i][j]->getBoundingBox().containsPoint(this->convertTouchToNodeSpace(touch))) {
        tiles[i][j] = nullptr;
        this->removeChild(tiles[i][j]);
     }
  }
}
return true;
}
1 Like

Thank you for your response, but now the the sprites clicked don’t go away at all.

Switch tiles[i][j] = nullptr; below this->removeChild(tiles[i][j]);

1 Like

Thank you very much, this works like a dream.