[Cocos2d-x For WP8]点击移动精灵
点击移动是游戏里面常用的操作,那么在Cocos2d-x里面可以通过setTouchEnabled(true)方法来设置接收屏幕的点击事件,然后添加ccTouchesEnded(CCSet* touches, CCEvent* event)方法处理点击后的操作,在方法体里面就可以获取点击的位置,然后通过动画的方式来移动精灵。
代码示例:
//在init方法里面初始化当前的实例 bool HelloWorld::init() { bool bRet = false; do { //CCLayer进行初始化,初始化失败跳出循环 if ( !CCLayer::init() ) { break; } //获取手机屏幕的大小 CCSize size = CCDirector::sharedDirector()->getWinSize(); CCSprite* sprite = CCSprite::create("cat.png"); CCLayer* layer = CCLayerColor::create(ccc4(255,255,0,255));//(); addChild(layer, -1); addChild(sprite, 0, 1); sprite->setPosition( CCPointMake(20,150) ); //跳的动画 sprite->runAction( CCJumpTo::create(4, CCPointMake(300,48), 100, 4) ); //页面颜色闪动的动画 layer->runAction( CCRepeatForever::create( (CCActionInterval*)( CCSequence::create( CCFadeIn::create(1), CCFadeOut::create(1), NULL) ) ) ); //接收界面的的触摸事件 setTouchEnabled(true); bRet = true; } while (0); //返回成功 return bRet; } void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event) { CCSetIterator it = touches->begin(); CCTouch* touch = (CCTouch*)(*it); //获取点击的位置 CCPoint location = touch->getLocationInView(); //把UIkit坐标转化为GL坐标 CCPoint convertedLocation = CCDirector::sharedDirector()->convertToGL(location); //获取节点 CCNode* s = getChildByTag(1); //移除所有的动画 s->stopAllActions(); //启动移动动画 s->runAction( CCMoveTo::create(1, CCPointMake(convertedLocation.x, convertedLocation.y) ) ); float o = convertedLocation.x - s->getPosition().x; float a = convertedLocation.y - s->getPosition().y; float at = (float) CC_RADIANS_TO_DEGREES( atanf( o/a) ); if( a < 0 ) { if( o < 0 ) at = 180 + fabs(at); else at = 180 - fabs(at); } //转动动画 s->runAction( CCRotateTo::create(1, at) ); }
运行的效果: