Search code examples
cocos2d-x

get a position of a sprite from another sprite


I have 2 sprite, spriteA and spriteB, one is added to HelloWord Layer and the other added to a node:

node = Node::create();   
this->addChild(node);

spriteA = Sprite::create("spriteA.png");
node->addChild(spriteA);

spriteB = Sprite::create("spriteB.png");
this->addChild(spriteB);

Then I need to move the node to spriteB center, and keep the spriteA position from the spriteB:

//get screen position of spriteA and (maybe not) position of spriteA from spriteB
Vec2 point = center->convertToWorldSpace(spriteA->getPosition());
Vec2 position = Vec2(point.x - SpriteB->getPositionX(), point.y - spriteB->getPositionY());

node->setPosition(spriteB->getPosition());
spriteA->setPosition(position);

But I can get the good position of the spriteA from the spriteB, someone can help please?


Solution

  • i tried this code, and it works

    auto posB = spriteB->getPosition();
    auto posA = spriteA->getPosition();
    auto dis = node->getPosition() - posB;
    node->setPosition(posB);
    spriteA->setPosition(posA + dis);
    

    if still not work, maybe you need to set node contentsize and anchorpoint