//初始化游戏层 bool GameLayer::init() { if ( !Layer::init() ) { return false; } auto labhelp = LabelTTF::create("this is game","宋体",15); labhelp->setPosition(Point(0,340)); this->addChild(labhelp); auto labback = LabelTTF::create("MainMenu","宋体",15); auto miback = MenuItemLabel::create(labback,[](Ref* sender) { Director::getInstance()->replaceScene(HelloWorld::createScene()); }); miback->setPosition(Point(360,200)); //接受触摸事件 auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan, this);//指定触摸的回调函数 listener->onTouchMoved = CC_CALLBACK_2(HelloWorld::onTouchMoved, this); listener->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);//将listener放入事件委托中 //初始化蛇头坐标和食物的坐标 sHead = new SnakeNode(); sHead->row = rand()%10; sHead->col = rand()%10; //初始化食物的坐标 sFood = new SnakeNode(); sFood->row = rand()%10; sFood->col = rand()%10; //执行定时任务 this->schedule(schedule_selector(GameLayer::logic01),0.5); return true; }
bool GameLayer::onTouchBegan(Touch* touch, Event *event) { auto p = touch->getLocation();//获取当前的触点 int nowrow; //当前用户触摸的行 nowrow = ((int)p.y)/32; int nowcol; //当前用户触摸的列 nowcol = ((int)p.x)/32; //如果触点的Y坐标相对于蛇头的Y坐标 大于 触点的X坐标相对于蛇头的X坐标,那么是上下移动,否则左右移动 if( abs(nowrow - sHead->row) > abs(nowcol - sHead->col)) //上下移动 { if(nowrow > sHead->row) { sHead->dir = DIR_DEF::UP; } else { sHead->dir=DIR_DEF::DOWN; } } else //左右移动 { if(nowcol > sHead->col) { sHead->dir=DIR_DEF::RIGHT; } else { sHead->dir=DIR_DEF::LEFT; } } CCLOG("rand %d",rand()); CCLOG("you touchbegan%f,%f",p.x,p.y); return true; }
Cocos2dx 3.0 过渡篇(二十五)死不了的贪食蛇(触摸版),布布扣,bubuko.com
Cocos2dx 3.0 过渡篇(二十五)死不了的贪食蛇(触摸版)
原文:http://blog.csdn.net/start530/article/details/23784985