您的位置:首页 > 移动开发 > Cocos引擎

cocos2d-x学习日志(6) --触屏事件

2013-08-24 17:32 381 查看
转载请标明:转载自【小枫栏目】,博文链接:http://blog.csdn.net/my183100521/article/details/10276991

一、简介

一般在菜单中,不是继承自CCLayer,这时候要检测触屏,就需要两步就可以完成

第一步:setIsTouchEnabled(true);这句话在类初始化的时候加入

第二步:重写相应的函数:

ccTouchesBegan(CCSet *pTouches,CCEvent *pEvent);//触屏开始事件

ccTouchesMoved(CCSet *pTouches,CCEvent *pEvent);//拖动事件

ccTouchesEnded(CCSet *pTouches,CCEvent *pEvent);//触屏结束事件

需要在哪个消息上作处理,就重写哪个函数就可以,具体的重写方法registerWithTouchDispatcher,如

void HelloWorld::registerWithTouchDispatcher(void)
{
CCDirector* pDirector = CCDirector::sharedDirector();
pDirector->getTouchDispatcher()->addTargetedDelegate(this, 0,true); //单点触摸
//pDirector->getTouchDispatcher()->addStandardDelegate(this, 0);//多点触摸
}


二、实例

1.主角随手移动,参考《Cocos2d-x 权威指南》里的例子。

HelloWorldScene.h

//add mumber
CCSprite* hero;
float deltax;
float deltay;
bool isControl;
//touch事件
std::string title();
void registerWithTouchDispatcher(void);
bool ccTouchBegan(CCTouch* touch,CCEvent* event);
void ccTouchMoved(CCTouch* touch,CCEvent* event);
void ccTouchEnded(CCTouch* touch,CCEvent* event);
void ccTouchCancelled(CCTouch* touch,CCEvent* event);
HelloWorldScene.cpp

std::string HelloWorld::title()
{
return "Targeted touches";
}

void HelloWorld::registerWithTouchDispatcher(void) { CCDirector* pDirector = CCDirector::sharedDirector(); pDirector->getTouchDispatcher()->addTargetedDelegate(this, 0,true); //单点触摸 //pDirector->getTouchDispatcher()->addStandardDelegate(this, 0);//多点触摸 }

bool HelloWorld::ccTouchBegan(cocos2d::CCTouch *touch, cocos2d::CCEvent *event)
{
CCLog("ccTouchBegan");
CCPoint heropos = hero->getPosition();
CCPoint location = touch->locationInView();
location = CCDirector::sharedDirector()->convertToGL(location);

if (location.x > heropos.x - 42.5 && location.x < heropos.x +42.5 && location.y > heropos.y - 60.5 && location.y <heropos.y +60.5) {
isControl = true;
deltax = location.x - heropos.x;
deltay = location.y - heropos.y;
}

return true;
}

void HelloWorld::ccTouchMoved(cocos2d::CCTouch *touch, cocos2d::CCEvent *event)
{
CCLog("ccTouchMoved");
if (isControl) {
CCPoint location = touch->locationInView();
location = CCDirector::sharedDirector()->convertToGL(location);

float x = location.x - deltax;
float y = location.y - deltay;

hero->setPosition(ccp(x,y));
}
}

void HelloWorld::ccTouchEnded(cocos2d::CCTouch *touch, cocos2d::CCEvent *event)
{
CCLog("ccTouchEnded");
isControl = false;
}

void HelloWorld::ccTouchCancelled(cocos2d::CCTouch *touch, cocos2d::CCEvent *event)
{
CCLog("ccTouchCancelled");
isControl = false;
}
在init()添加代码:

hero = CCSprite::create("Role.png");
this->addChild(hero);

//registerWithTouchDispatcher();
this->setTouchEnabled(true);

注:若setTouchEnabled(),没调用registerWithTouchDispatcher,直接引用注册函数吧~~

效果图:





今天的博文就写到这里,若有不好之处,望各大网友留言赐教,大家交流下~~

参考博文:http://blog.csdn.net/bill_man/article/details/7214667
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Cocos2d-x