触摸事件是做cocos2d-x的基础。比如做新手引导。物品的拖动。弹窗的屏蔽层。诸如此类.做触摸事件,不要抱着试一试的心态下手,一定要弄透彻,不然出现问题了,你再试一试其实时间花的更多
触摸事件主要需要弄清的事情
- 是否吞噬setSwallowTouches
- onTouchBegin返回的意义
代码如下:
#include "HelloWorldScene.h"
USING_NS_CC;
Scene* HelloWorld::createScene()
{
auto scene = Scene::create();
auto layer = HelloWorld::create();
scene->addChild(layer);
return scene;
}
bool HelloWorld::init()
{
if ( !Layer::init() )
{
return false;
}
Size winSize = Director::getInstance()->getWinSize();
auto sprite = Sprite::create("HelloWorld.png");
sprite->setPosition(Vec2(winSize.width / 2,winSize.height / 2 ));
this->addChild(sprite,0);
m_nvShenSp = Sprite::create("nvshen.jpg");
m_nvShenSp->setPosition(Vec2(winSize.width / 2,winSize.height / 2));
this->addChild(m_nvShenSp);
addTouchEvent();
return true;
}
//添加触摸事件
void HelloWorld::addTouchEvent(){
auto dispatcher = Director::getInstance()->getEventDispatcher();
auto listener1 = EventListenerTouchOneByOne::create();
listener1->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan,this);
listener1->onTouchMoved = CC_CALLBACK_2(HelloWorld::onTouchMoved,this);
listener1->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded,this);
listener1->setSwallowTouches(true);//设置吞噬按钮
//给Layer添加触摸事件
dispatcher->addEventListenerWithSceneGraPHPriority(listener1,this);
};
bool HelloWorld::onTouchBegan(Touch *touch,Event *unused_event){
log("onTouchBegan");
Point touchPoint = touch->getLocation();
Rect nvShenRect = m_nvShenSp->getBoundingBox();//这个函数的内部,其实是给你一个Rect大小,一个在父类的Point
if (nvShenRect.containsPoint(touchPoint)) //如果点击的点落在女神图片上(因为他们同属于一个父控件layer所以可以这么转换,否则请查看坐标转换)
{
return false;//false就往下传递,被按钮吃掉,onTouchMoved,onTouchEnded接收不到
}
return true; //如果没有点击到女神的图片上,就不往下传递,不往下传递,被onTouchMoved,onTouchEnded接收
};
void HelloWorld::onTouchMoved(Touch *touch,Event *unused_event){
log("onTouchMoved");
};
void HelloWorld::onTouchEnded(Touch *touch,Event *unused_event){
log("onTouchEnded");
};
void HelloWorld::onTouchCancelled(Touch *touch,Event *unused_event){
};
原文链接:https://www.f2er.com/cocos2dx/341679.html