cocos2d-x触摸事件(二)
发布时间:2020-12-14 16:48:31 所属栏目:百科 来源:网络整理
导读:xxx.h文件: bool onMapTouchBegan(cocos2d ::Touch * touch,cocos2d ::Event * event); void onMapTouchMove(cocos2d ::Touch * touch,cocos2d ::Event * event); void onMapTouchEnded(cocos2d ::Touch * touch,cocos2d ::Event * event); xxx.cpp文件: /
xxx.h文件: bool onMapTouchBegan(cocos2d::Touch *touch,cocos2d::Event *event);
void onMapTouchMove(cocos2d::Touch *touch,cocos2d::Event *event);
void onMapTouchEnded(cocos2d::Touch *touch,cocos2d::Event *event);
xxx.cpp文件: //二:在大地图(imgMap)上添加2个建筑物(room1、room2)
ImageView* room1 = ImageView::create("MainMap/room1.png");
imgMap->addChild(room1);
room1->setAnchorPoint(Vec2(0.5,0.5));
room1->setPosition(Vec2(1380,814));
ImageView* room2 = ImageView::create("MainMap/room2.png");
imgMap->addChild(room2);
room2->setAnchorPoint(Vec2(0.5,0.5));
room2->setPosition(Vec2(1000,814));
//1.单点触摸
auto mapOneByOne = EventListenerTouchOneByOne::create();
mapOneByOne->setSwallowTouches(true);//其它事件都吞没掉(点击一个对象,其它对象的事件是否被吞没)
mapOneByOne->onTouchBegan = CC_CALLBACK_2(MainMap::onMapTouchBegan,this);
mapOneByOne->onTouchMoved = CC_CALLBACK_2(MainMap::onMapTouchMove,this);
mapOneByOne->onTouchEnded = CC_CALLBACK_2(MainMap::onMapTouchEnded,this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(mapOneByOne,room1);
_eventDispatcher->addEventListenerWithSceneGraphPriority(mapOneByOne->clone(),room2);
bool MainMap::onMapTouchBegan(cocos2d::Touch * touch,cocos2d::Event * event)
{
CCLOG("onMapTouchBegan");
auto target = (ImageView*)event->getCurrentTarget();
Vec2 v1 = touch->getLocation();
Vec2 locationInNode = target->convertToNodeSpace(v1);//转换坐标原点为当前对象左下角
Size s = target->getContentSize();
Rect rect = Rect(0,0,s.width,s.height);
if (rect.containsPoint(locationInNode)) {
//如果点中本对象,返回true
return true;
}
return false;
}
void MainMap::onMapTouchMove(cocos2d::Touch * touch,cocos2d::Event * event)
{
//onMapTouchBegan返回true时执行此方法。
CCLOG("onMapTouchMove");
//手指滑动的位置距离
Vec2 diff = touch->getDelta();
//建筑原来的位置
auto target = (ImageView*)event->getCurrentTarget();
Vec2 posSrc = target->getPosition();
//滑动后的位置
Vec2 posDes = posSrc + diff;
////判断不能拖到屏幕以外
//if (posDes.x >= 1280) {
// posDes.x = 1280;
//}
//if (posDes.y >= 814) {
// posDes.y = 814;
//}
//if (posDes.x <= (960 - 1280)) {
// posDes.x = 960 - 1280;
//}
//if (posDes.y <= (640 - 814)) {
// posDes.y = 640 - 814;
//}
target->setPosition(posDes);
}
void MainMap::onMapTouchEnded(cocos2d::Touch * touch,cocos2d::Event * event)
{
CCLOG("onMapTouchEnded");
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |