天天看点

多点触摸缩放层

cocos2dx3.2中,

cocos2dx多点触摸的注册

mlistener = EventListenerTouchAllAtOnce::create();
    mlistener->onTouchesBegan = CC_CALLBACK_2(OneTiledLayer::onTouchesBegan, this);
    mlistener->onTouchesCancelled = CC_CALLBACK_2(OneTiledLayer::onTouchesCancelled, this);
    mlistener->onTouchesEnded = CC_CALLBACK_2(OneTiledLayer::onTouchesEnded, this);
    mlistener->onTouchesMoved = CC_CALLBACK_2(OneTiledLayer::onTouchesMoved, this);
    Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(mlistener, this);
           

私有变量:

Vec2 tPoint;//进图坐标,用来控制多点缩放
    Vec2 cPoint;//此时屏幕坐标,用来控制单点偏移
    Vec2 sPoint1;//多点触控,前两个点
    Vec2 sPoint2;
    float sScale;//点击时候屏幕缩放量
           

当多点触的时候,应该根据距离缩放屏幕,单点触的时候,应根据拖动移动屏幕

void OneTiledLayer::onTouchesBegan(const std::vector<Touch*>& touches, Event *unused_event)
{
    CCLOG("%zd",touches.size());
    
    cPoint = this->getPosition();
    if (touches.size()>1) {
        sPoint1 = touches.at(0)->getLocation();
        sPoint2 = touches.at(1)->getLocation();
        sScale = this->getScale();
        tPoint = this->getPosition();
        tPoint = Vec2(tPoint.x/sScale, tPoint.y/sScale);
    }
}
void OneTiledLayer::onTouchesMoved(const std::vector<Touch*>& touches, Event *unused_event)
{
    if (touches.size()>1) {
        Vec2 point1 = touches.at(0)->getLocation();
        Vec2 point2 = touches.at(1)->getLocation();
        float distance1 = getDistanceBetween(point1, point2);
        float distance2 = getDistanceBetween(sPoint1, sPoint2);
        float sca = distance1/distance2*sScale;
        this->setScale(sca);
        this->setPosition(tPoint.x*sca,tPoint.y*sca);
    }
    else{
        Vec2 startPoint = touches.at(0)->getStartLocation();
        Vec2 touchPoint = touches.at(0)->getLocation();
        Vec2 movePoint = Vec2(touchPoint.x-startPoint.x+cPoint.x, touchPoint.y-startPoint.y+cPoint.y);
        this->setPosition(movePoint);
    }
}
           

ok了,可以看效果啦

继续阅读