Sprite添加触摸监听(实现跟随手指移动)

auto plane = Sprite::create("mplane.png");
auto touchListener = EventListenerTouchOneByOne::create();
    touchListener->onTouchBegan = CC_CALLBACK_2(PlanLayer::onTouchBegan, this);
    touchListener->onTouchMoved = CC_CALLBACK_2(PlanLayer::onTouchMoved, this);
    touchListener->onTouchEnded = CC_CALLBACK_2(PlanLayer::onTouchEnded, this);
    _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener,plane); 
bool PlanLayer::onTouchBegan(Touch *touch, Event *unused_event){
    auto target = static_cast<Sprite*>(unused_event->getCurrentTarget());//将派生类指针转化成基类
    Point locationInNode = target->convertToNodeSpace(touch->getLocation());//将世界坐标转化成节点坐标
    target->setPosition(touch->getLocation());
    return true;
}
void PlanLayer::onTouchMoved(Touch *touch, Event *unused_event){
    auto target = static_cast<Sprite*>(unused_event->getCurrentTarget());
    target->setPosition(touch->getLocation());
}
void PlanLayer::onTouchEnded(Touch *touch, Event *unused_event){
}  

你可能感兴趣的:(类,游戏开发,cocos2d-x,Visual,Studio)