Hiya, newbie alert.
Project build: Cocos2D-X version 4.6.3.
I’ve jumped into learning app development right when there was a version update and so far have found it very difficult to find resources to accomplish what I’m trying to do. Simply:
- have a sprite image load on the screen - check
- on touchesbegan, have a child sprite spawn from that image - check
- be able to drag that child sprite around the screen - no check
- be able to repeat that process with a ’toolbox. of images - not there yet
Been trying multiple variations but not the right one yet:
void GameLayer::ccTouchesBegan(CCSet* pTouches, CCEvent* event)
{
CCSetIterator i;
GameSprite * image;
CCTouch *touch;
CCPoint tap;
//loop through all beginning touches
for( i = pTouches->begin(); i != pTouches->end(); i++)
{
touch = (CCTouch*) (*i);
if (touch)
{
//get location in OpenGL view
tap = touch->getLocation();
for (int p = 0; p < 1; p++)
{
image = (GameSprite *) _images->objectAtIndex(p);
if (image->boundingBox().containsPoint(tap))
{
//store player's touch
image->setTouch(touch);
//add image
_child = GameSprite::gameSpriteWithFile("HelloWorld.png");
//change the numbers here to change position of sprite
_child->setPosition(ccp(_screenSize.width * 0.5f, _screenSize.height * 0.5f));
this->addChild(_child);
_images = CCArray::create(_child, NULL);
_images->retain();
}
}
}
}
}
void GameLayer::ccTouchesMoved(CCSet *pTouches, CCEvent *event)
{
CCSetIterator i;
//GameSprite * image;
CCTouch *touch;
CCPoint tap;
//loop through all beginning touches
for( i = pTouches->begin(); i != pTouches->end(); i++)
{
touch = (CCTouch*) (*i);
if (touch)
{
tap = touch->getLocation();
for (int p = 0; p < _images->count(); p++)
{
_child = (GameSprite *) _images->objectAtIndex(p);
//if touch belongs to player
if (_child->getTouch() != NULL && _child->getTouch() == touch)
{
CCPoint nextPosition = tap;
_child->setNextPosition(nextPosition);
_child->setVector(ccp(tap.x - _child->getPositionX(), tap.y - _child->getPositionY()));
}
}
}
}
}
void GameLayer::ccTouchesEnded(CCSet *pTouches, CCEvent *event)
{
CCSetIterator i;
GameSprite * image;
CCTouch *touch;
//loop through all beginning touches
for( i = pTouches->begin(); i != pTouches->end(); i++)
{
touch = (CCTouch*) (*i);
if (touch)
{
for (int p = 0; p < _images->count(); p++)
{
image = (GameSprite *) _images->objectAtIndex(p);
if (image->getTouch() != NULL && image->getTouch() == touch)
{
//if touch ending belongs to this player, clear it
image->setTouch(NULL);
image->setVector(CCPointZero);
}
}
}
}
}
void GameLayer::update (float dt)
{
//GameSprite * image;
CCPoint objectNextPosition;
CCPoint objectVector;
for (int p = 0; p < _images->count(); p++)
{
_child = (GameSprite *) _images->objectAtIndex(p);
objectNextPosition = _child->getNextPosition();
objectVector = _child->getVector();
}
//move image to next position
_child->setPosition(_child->getNextPosition());
}
Let me know if more is needed… Thanks!