首页 > 代码库 > Cocos2d-x3.2 多点触控
Cocos2d-x3.2 多点触控
//GameScene.h #include "cocos2d.h" USING_NS_CC; class GameScene : public cocos2d::Layer { public: static cocos2d::Scene* createScene(); virtual bool init(); virtual void onTouchesBegan(const std::vector<Touch*>& touches, Event *unused_event); virtual void onTouchesMoved(const std::vector<Touch*>& touches, Event *unused_event); virtual void onTouchesEnded(const std::vector<Touch*>& touches, Event *unused_event); virtual void onTouchesCancelled(const std::vector<Touch*>&touches, Event *unused_event); void menuCallback(Ref* pSender); CREATE_FUNC(GameScene); private: //注意不能用auto关键字 Size size; Sprite *sprite; };
//GameScene.cpp //可参考MutiTouchTest.cpp #include "GameScene.h" USING_NS_CC; cocos2d::Scene* GameScene::createScene() { auto scene = Scene::create(); //创建一个场景 auto layer = GameScene::create(); //创建一个图层 scene->addChild(layer); return scene; } //初始化当前的图层 bool GameScene::init() { if(!Layer::init()) //初始化父类 return false; //获取屏幕大小 size = Director::getInstance()->getVisibleSize(); //auto size = Director::getInstance()->getWinSize(); auto sprite = Sprite::create("Icon.png"); sprite->setPosition(Vec2(size.width/2, size.height/2)); sprite->setTag(12); this->addChild(sprite); //1.注册监听事件对象 auto listener = EventListenerTouchAllAtOnce::create(); //多点触摸 //2.定义监听对象的回调方法 listener->onTouchesBegan = CC_CALLBACK_2(GameScene::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(GameScene::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(GameScene::onTouchesEnded, this); listener->onTouchesCancelled = CC_CALLBACK_2(GameScene::onTouchesCancelled, this); //3.在事件监听器中注册(事件监听器包含:触摸事件、键盘相应事件、加速记录事件、鼠标响应事件、自定义事件) _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); return true; } void GameScene::menuCallback(Ref* pSender) { } void GameScene::onTouchesBegan(const std::vector<Touch*>& touches, Event *unused_event) { for (auto &item: touches) //遍历容器中的各个成员!!!多点触摸时将显示同时显示多个精灵 { auto touch = item; auto location = touch->getLocation(); auto sprite = this->getChildByTag(12); sprite->setPosition(location); } } void GameScene::onTouchesMoved(const std::vector<Touch*>& touches, Event *unused_event) { } void GameScene::onTouchesEnded(const std::vector<Touch*>& touches, Event *unused_event) { } void GameScene::onTouchesCancelled(const std::vector<Touch*>&touches, Event *unused_event) { }
备注:关键掌握对容器touches中成员的遍历。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。