您的位置:首页 > 移动开发 > Cocos引擎

03.cocos2d-x触摸事件(二)

2015-12-27 20:32 351 查看
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");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cocos2d-x