cocos2dx 触屏事件
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !CCLayer::init() ) { return false; } CCSprite * spr = CCSprite::create("Icon.png"); spr->setPosition(ccp(150, 200)); addChild(spr, 0 , 922); return true; } // 重写触屏回调函数 bool HelloWorld:: ccTouchBegan(CCTouch * touch ,CCEvent * event) { CCLOG("ccTouchBegan"); return true; } void HelloWorld:: ccTouchMoved(CCTouch * touch ,CCEvent * event) { CCLOG("ccTouchMoved"); } void HelloWorld:: ccTouchEnded(CCTouch * touch ,CCEvent * event) { CCLOG("ccTouchEnded"); // 获取离开屏幕时对应的坐标 CCPoint point = touch->getLocation(); // 获取到的tag=922精灵 CCSprite * sp= (CCSprite*)this->getChildByTag(922); // 暂停所有动作 sp->stopAllActions(); // 执行move动作到用户离开的位子 sp->runAction(CCMoveTo::create(1, point)); } // 重写生命周期函数 void HelloWorld:: onEnter() { CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, false); CCLayer::onEnter(); } void HelloWorld:: onExit() { CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this); CCLayer::onExit(); }
.h
using namespace cocos2d; class HelloWorld : public cocos2d::CCLayer { public: // Method 'init' in cocos2d-x returns bool, instead of 'id' in cocos2d-iphone (an object pointer) virtual bool init(); // there's no 'id' in cpp, so we recommend to return the class instance pointer static cocos2d::CCScene* scene(); CREATE_FUNC(HelloWorld); // 重写触屏回调函数 virtual bool ccTouchBegan(CCTouch * touch ,CCEvent * event); virtual void ccTouchMoved(CCTouch * touch ,CCEvent * event); virtual void ccTouchEnded(CCTouch * touch ,CCEvent * event); // 重写生命周期函数 virtual void onEnter(); virtual void onExit(); };