//添加飞机
auto spPlane = Sprite::create();
spPlane->setTag(110);
spPlane->setPosition(Point(160,240));
this->addChild(spPlane);
//飞机动起来 。
Vector<SpriteFrame*> allframe;//保存所有帧
for(int i=0;i<2;i++){
SpriteFrame * sf = SpriteFrame::create("plane.png",Rect(i*60,0,60,75));//截取图片的一部分
allframe.pushBack(sf);
}
Animation * ani = Animation::createWithSpriteFrames(allframe,0.1);
spPlane->runAction(RepeatForever::create(Animate::create(ani)));
//添加触摸事件 控制飞机移动
EventListenerTouchOneByOne * event = EventListenerTouchOneByOne::create();
event->setSwallowTouches(true);
event->onTouchBegan= CC_CALLBACK_2(GameScene::onTouchBegan,this);
event->onTouchMoved= CC_CALLBACK_2(GameScene::onTouchMoved,this);
event->onTouchEnded= CC_CALLBACK_2(GameScene::onTouchEnded,this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(event,this); //注册到消息宣发器中。
需要添加 。飞机移动的三个状态的函数。
/* 移动飞机函数 */
bool GameScene::onTouchBegan(Touch *touch, Event *unused_event){
px = touch->getLocation().x; //获得当前坐标点x
py = touch->getLocation().y; //获得当前坐标点y
return true;
}
void GameScene::onTouchMoved(Touch *touch, Event *unused_event){
int mx=touch->getLocation().x-px;
int my=touch->getLocation().y-py;
auto spPlane = this->getChildByTag(110);//获得飞机 。
spPlane->runAction(MoveBy::create(0,Point(mx,my)));//飞机根据移动的坐标量 改变
px = touch->getLocation().x;
py = touch->getLocation().y;
}
void GameScene::onTouchEnded(Touch *touch, Event *unused_event){
}