
[历史归档]本文原发布于 cstriker1407.info 个人博客内容为历史存档仅供参考。发布时间2014-01-21 标题cocos2dx转盘吸附效果分类编程 / C C / cocos2dx 标签cocos2dx·吸附效果cocos2dx转盘吸附效果转盘吸附效果的大致实现首先是两个转盘的旋转函数然后重写Layer的触摸备注最近项目中用到了cocos2dx来开发一个基于陀螺仪的demo忙了半个星期一边学习一边开发总算搞了出来。这里备份下开发中学习到的一些cocos2dx知识。转盘吸附效果的大致实现demo中用到了一个圆形的转盘并且要求转盘转动时会吸附。这里备份下大致的代码实现首先是两个转盘的旋转函数voidXX::switchCircleA(floatangle){floatoldcircleSprite-getRotation();if(fabsf(old-angle)5){return;}floatspeed360/0.3f;floattimeNeedfabsf(old-angle)/speed;circleSprite-stopAllActions();CCRotateTo*rotateToCCRotateTo::create(timeNeed,angle);circleSprite-runAction(rotateTo);}voidXX::switchCircleB(){intanglecircleSprite-getRotation();if(angle0){angleangle360;}if(angle%9045){angle(angle/901)*90;}else{angle(angle/90)*90;}intspriteIdxangle/90;switch(spriteIdx){case0:case4:{//funA()break;}case1:{//funB()break;}case2:{//funC()break;}case3:{//funD()break;}break;default:}circleSprite-stopAllActions();CCRotateTo*rotateToCCRotateTo::create(0.5f,angle);CCEaseBackOut*easeCCEaseBackOut::create(rotateTo);circleSprite-runAction(ease);}然后重写Layer的触摸//使能触摸beginthis-setTouchEnabled(true);//endvoidXX::ccTouchesBegan(CCSet*pTouches,CCEvent*pEvent){if(pTouches-count()!1){return;}CCTouch*curTouch(CCTouch*)(pTouches-anyObject());cocos2d::CCPoint currTouchPointcurTouch-getLocation();//计算起始触摸偏移角度initOffsetAngle//计算起始转盘已经旋转的角度initAngleCCPoint centerXXXX;initOffsetAngleccpToAngle(ccpSub(currTouchPoint,center));initOffsetAngleCC_RADIANS_TO_DEGREES(initOffsetAngle);initAnglecircleSel-getRotation();。。}voidXX::ccTouchesMoved(CCSet*pTouches,CCEvent*pEvent){if(pTouches-count()!1){return;}CCTouch*curTouch(CCTouch*)(pTouches-anyObject());CCPoint newPointcurTouch-getLocation();//防止回调过快导致转盘闪动按一定策略丢弃部分Move回调。。//根据起始触摸偏移角度转盘起始角度当前触摸点偏移角度计算转盘的当前角度angleCCPoint centerXXXX;floatnewAngleccpToAngle(ccpSub(newPoint,center));newAngleCC_RADIANS_TO_DEGREES(newAngle);angle-newAngleinitOffsetAngleinitAngle;switchCircleA(angle);}voidXX::ccTouchesEnded(CCSet*pTouches,CCEvent*pEvent){switchCircleB();}voidXX::ccTouchesCancelled(CCSet*pTouches,CCEvent*pEvent){switchCircleB();}备注由于时间紧张作者没有在网上仔细寻找现成代码 而是自己写了一套感觉效果还不错就没有再搜索其他方案。