cocos2dx Sprite触摸监听

1、让Sprite绑定触摸监听器

//create a sprite
auto sprite = Sprite::create("whiteSprite.png");
sprite->setPosition(s_centre);
addChild(sprite);

// Make sprite touchable
auto listener1 = EventListenerTouchOneByOne::create();
listener1->setSwallowTouches(true);
listener1->onTouchBegan = [](Touch* touch, Event* event){
    auto target = static_cast<Sprite*>(event->getCurrentTarget());

    Vec2 locationInNode = target->convertToNodeSpace(touch->getLocation());
    Size s = target->getContentSize();
    Rect rect = Rect(0, 0, s.width, s.height);
    if (rect.containsPoint(locationInNode))
    {
        log("sprite began... x = %f, y = %f", locationInNode.x, locationInNode.y);
        target->setOpacity(180);
        return true;
    }
    return false;
};

listener1->onTouchMoved = [](Touch* touch, Event* event){
    auto target = static_cast<Sprite*>(event->getCurrentTarget());
    target->setPosition(target->getPosition() + touch->getDelta());
};

listener1->onTouchEnded = [=](Touch* touch, Event* event){
};

_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, sprite);

2、如果该Sprite有子类,则子类会相对一起移动,添加代码。

//create second sprite
auto sprite2 = Sprite::create("whiteSprite.png");
sprite2->setPosition(s_centre);
sprite->addChild(sprite2);

3、当sprite移动时,sprite2也相对一起移动。

你可能感兴趣的:(cocos2dx)