cocos2d-x aplha3.0中添加touch事件

xiaoxiao2021-03-01  2

如果你想在layer子类里像原来那样override CClayer里的这几个函数:

// Deprecated touch callbacks. CC_DEPRECATED_ATTRIBUTE virtual bool ccTouchBegan(Touch *pTouch, Event *pEvent) final{CC_UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent); return false;}; CC_DEPRECATED_ATTRIBUTE virtual void ccTouchMoved(Touch *pTouch, Event *pEvent) final{CC_UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} CC_DEPRECATED_ATTRIBUTE virtual void ccTouchEnded(Touch *pTouch, Event *pEvent) final{CC_UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} CC_DEPRECATED_ATTRIBUTE virtual void ccTouchCancelled(Touch *pTouch, Event *pEvent) final{CC_UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesBegan(Set *pTouches, Event *pEvent) final{CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesMoved(Set *pTouches, Event *pEvent) final{CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} 你会发现编译错误,因为C++11的新关键字final被添加上去了,不允许被重载了。

那该怎么办呢?

cocos2d-x增加了新的机制来添加事件:

举个例子就明白了:

void OptionLayer::createEventListener() { auto dispatcher = EventDispatcher::getInstance(); auto listener = EventListenerTouch::create(Touch::DispatchMode::ALL_AT_ONCE); listener->onTouchesBegan = CC_CALLBACK_2(OptionLayer::myTouchesBegan, this) ; listener->onTouchesMoved = CC_CALLBACK_2(OptionLayer::myTouchesMoved, this) ; listener->onTouchesEnded = CC_CALLBACK_2(OptionLayer::myTouchesEnded, this) ; dispatcher->addEventListenerWithSceneGraphPriority(listener, this); }

void OptionLayer::myTouchesBegan( const std::vector<Touch*>& ts, Event* event ) { auto winSize = Director::getInstance()->getWinSize(); auto iter = ts.begin(); while (iter != ts.end()) { Touch *t = (Touch*)(*iter); Point p = t->getLocation(); // left,当触控操作的起点小于屏幕宽度的一半,说明触控发生在左屏 if (p.x <= winSize.width / 2) { _activityJoystick(p); } else { // right,否则发生在右屏,会产生“攻击”信号 _delegator->onAttack(); } iter++; } } 好了,注意lamba函数的建立,一般按照上面建立比较好!

转载请注明原文地址: https://www.6miu.com/read-3850046.html

最新回复(0)