cocos2d-x触摸事件(二)

前端之家收集整理的这篇文章主要介绍了cocos2d-x触摸事件(二)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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");
}
原文链接:https://www.f2er.com/cocos2dx/340514.html

猜你在找的Cocos2d-x相关文章