首先创建侦听事件:
<span style="white-space:pre"> </span>auto listen = EventListenerTouchOneByOne::create();
listen->onTouchBegan = CC_CALLBACK_2(Plane1::onTouchBegan, this);
listen->onTouchMoved = CC_CALLBACK_2(Plane1::onTouchMoved, this);
listen->onTouchEnded = CC_CALLBACK_2(Plane1::onTouchEnded, this);
listen->onTouchCancelled = CC_CALLBACK_2(Plane1::onTouchCancelled, this);
listen->setSwallowTouches(true);
然后为对象写上点击事件,判断对象是否在点上,写上方法:
<span style="color: rgb(255, 0, 0); white-space: pre;"> </span>listen->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)){
return true;
}
return false;
};
移动方法,判断点击后移动对象:
listen->onTouchMoved = [](Touch* touch, Event* event){}
auto target = static_cast<Sprite*>(event->getCurrentTarget()); //获得对象getCurrentTarget();
target->setPosition(target->getPosition() + touch->getDelta()); //偏移getDelta();
Size visibleSize = Director::getInstance()->getVisibleSize();
Point origin = Director::getInstance()->getVisibleOrigin();<pre name="code" class="cpp">}
在移动方法里写上屏幕大小的适配,目的就是防止对象移动到场景外:
/*X轴*/
if (target->getPositionX() + touch->getDelta().x >= visibleSize.width - target->getContentSize().width / 2){
target->setPositionX(visibleSize.width - target->getContentSize().width / 2);
}
else if (target->getPositionX() + touch->getDelta().x <= target->getContentSize().width / 2){
target->setPositionX(target->getContentSize().width / 2);
}
else{
target->setPositionX(target->getPositionX() + touch->getDelta().x);
}
/*Y轴*/
if (target->getPositionY() + touch->getDelta().y >= visibleSize.height - target->getContentSize().height / 2){
target->setPositionY(visibleSize.height - target->getContentSize().height / 2);
}
else if (target->getPositionY() + touch->getDelta().y <= target->getContentSize().height / 2){
target->setPositionY(target->getContentSize().height / 2);
}
else{
target->setPositionY(target->getPosition().y + touch->getDelta().y);
}<span style="color:#ff0000;">
</span>
首先target获取到点击的对象,然后判断它移动是否超出场景边界,当它超出边界时就默认它为最大边界,这样子就可以让它保持最大边界的极限值,从而达到效果。这里就是点击事件的代码,还有边界问题,有一些头文件的调用就在这里省略了,具体的方法可以去查看cocos的API,参照这里就知道它的具体使用。