在HelloWorldScene.h中声明
class HelloWorld : public cocos2d::CCLayer
{ public: ...... CCPoint convertToGL(CCSet *pTouches); virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *event); private: CCSprite *m_pSprite; }; |
在HelloWorldScene.cpp中作如下声明
// on "init" you need to initialize your instance
bool HelloWorld::init() { bool bRet = false; do { CC_BREAK_IF(! CCLayer::init()); ...... //MYCode m_pSprite = CCSprite::create("luffy.png"); //CCSize size=CCDirector::sharedDirector()->getWinSize();//note m_pSprite->setPosition(ccp(size.width / 2, size.height / 2)); this->addChild(m_pSprite, 1); //note this->setTouchEnabled(true); bRet = true; } while (0); return bRet; } |
CCPoint HelloWorld::convertToGL(CCSet *pTouches)
{ if(pTouches) { CCSetIterator it = pTouches->begin(); CCTouch *touch = (CCTouch *)(*it); CCPoint m_tBeginPos = touch->locationInView(); m_tBeginPos = CCDirector::sharedDirector()->convertToGL(m_tBeginPos); return m_tBeginPos; } assert("pTouches is NULL"); } void HelloWorld::ccTouchesMoved(CCSet *pTouches, CCEvent *event) { CCPoint touch_pos = convertToGL(pTouches); CCPoint cur_pos = m_pSprite->getPosition(); if(ccpDistance(touch_pos, cur_pos) != 0) { int dx = touch_pos.x - cur_pos.x; int dy = touch_pos.y - cur_pos.y; CCPoint vector = CCPoint::CCPoint(dx, dy); double dist = sqrt(dx * dx + dy * dy * 1.0); //note CCPoint unit_vector = CCPoint::CCPoint(dx / dist, dy / dist); int speed = 1; m_pSprite->setPosition(ccp(cur_pos.x + unit_vector.x * speed, cur_pos.y + unit_vector.y * speed)); } } |
程序实现的效果是
sprite会以规定的速度向鼠标所在位置靠近