cocos2dx学习笔记(1)之触摸移动精灵
首先在VS2010中创建一个cocos2dx项目,确保其能正常编译运行
然后在HelloWorld头文件中申明重载虚方法:
添加引用【#include "cocos2d.h"】和【USING_NS_CC;】,并在public中添加下列申明:
virtual void registerWithTouchDispatcher();//注册触屏事件监听
virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);// 必须实现
virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);
virtual void ccTouchEnded(CCTouch *pTouch,CCEvent *pEvent);
virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent);
最后在CPP的init()方法中开启触屏事件监听:
setTouchEnabled(true);
实现头文件虚方法:
void HelloWorld::registerWithTouchDispatcher(){
//注册触屏事件监听
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
}
bool HelloWorld::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent){
//更新精灵位置
sprite->setPosition(pTouch->getLocation());
return true;
}
void HelloWorld::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent){
//更新精灵位置
sprite->setPosition(pTouch->getLocation());
}
void HelloWorld::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent){
}
void HelloWorld::ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent){
}