cocos2d-x 精灵移动
来源:未知 责任编辑:责任编辑 发表时间:2013-11-15 19:48 点击:次
在HelloWorldScene.h中声明
p>
p>class HelloWorld : public cocos2d::CCLayer
p>{
p>public:
p> ......
p> CCPoint convertToGL(CCSet *pTouches);
p> virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *event);
p>private:
p> CCSprite *m_pSprite;
p>};
p>
p>在HelloWorldScene.cpp中作如下声明
p>
p>
p>
p>// on "init" you need to initialize your instance
p>bool HelloWorld::init()
p>{
p> bool bRet = false;
p> do
p> {
p> CC_BREAK_IF(! CCLayer::init());
p> ......
p> //MYCode
p> m_pSprite = CCSprite::create("luffy.png");
p> //CCSize size=CCDirector::sharedDirector()->getWinSize();//note
p> m_pSprite->setPosition(ccp(size.width / 2, size.height / 2));
p> this->addChild(m_pSprite, 1); //note
p> this->setTouchEnabled(true);
p>
p> bRet = true;
p> }
p> while (0);
p>
p> return bRet;
p>}
p>
p>
p>
p>CCPoint HelloWorld::convertToGL(CCSet *pTouches)
p>{
p> if(pTouches)
p> {
p> CCSetIterator it = pTouches->begin();
p> CCTouch *touch = (CCTouch *)(*it);
p> CCPoint m_tBeginPos = touch->locationInView();
p> m_tBeginPos = CCDirector::sharedDirector()->convertToGL(m_tBeginPos);
p> return m_tBeginPos;
p> }
p> assert("pTouches is NULL");
p>}
p>void HelloWorld::ccTouchesMoved(CCSet *pTouches, CCEvent *event)
p>{
p> CCPoint touch_pos = convertToGL(pTouches);
p> CCPoint cur_pos = m_pSprite->getPosition();
p> if(ccpDistance(touch_pos, cur_pos) != 0)
p> {
p> int dx = touch_pos.x - cur_pos.x;
p> int dy = touch_pos.y - cur_pos.y;
p> CCPoint vector = CCPoint::CCPoint(dx, dy);
p> double dist = sqrt(dx * dx + dy * dy * 1.0); //note
p> CCPoint unit_vector = CCPoint::CCPoint(dx / dist, dy / dist);
p> int speed = 1;
p> m_pSprite->setPosition(ccp(cur_pos.x + unit_vector.x * speed, cur_pos.y + unit_vector.y * speed));
p> }
p>}
p>
p>程序实现的效果是
p>
p>sprite会以规定的速度向鼠标所在位置靠近
p>
p>
p>
相关新闻>>
最新推荐更多>>>
- 发表评论
-
- 最新评论 更多>>