bool FirstScene::init()
{
if (!Layer::init())
{
return false;
}
Size winSize=Director::getInstance()->getWinSize();
log("winSize.width:%f,winSize.height:%f",winSize.width,winSize.height);
auto bg = Sprite::create("firstScreen/bg0.jpg");
bg->setPosition(ccp(winSize.width/2,winSize.height/2));
addChild(bg);
auto btn = ui::Button::create();
auto btn1 = Button::create();
startBt = Sprite::create("firstScreen/startGame.png");
startBt->setPosition(ccp(winSize.width/2,winSize.height/2));
addChild(startBt);
setTouchEnabled(true);//打开触摸开关
setTouchMode(Touch::DispatchMode::ONE_BY_ONE);//触摸模式为为单点触摸
//注册监听
auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan=CC_CALLBACK_2(FirstScene::onTouchBegan,this);
listener->onTouchEnded=CC_CALLBACK_2(FirstScene::onTouchEnded,this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener,this);
return true;
}
在init()中做初始化工作
void FirstScene::onTouchEnded(Touch *touch, Event *unused_event)
{
auto pos = touch->getLocationInView(); //获取相对于左上角的坐标值
pos = startBt->convertToNodeSpace(pos); //转化为相对于startBt的值
CCSize sz = startBt->getTexture()->getContentSizeInPixels();
CCRect rect = CCRectMake(0,0,sz.width,sz.height);//Bt所覆盖的区域
if (rect.containsPoint(pos))
{
log("ok");
}
}
以上为精灵触摸控制