zoukankan      html  css  js  c++  java
  • cocos2d-x 精灵移动

    在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会以规定的速度向鼠标所在位置靠近

  • 相关阅读:
    InApp PurchaseVerifying Store Receipts[6]
    InApp PurchaseTesting a Store [7]
    App Store Review Guidelines
    JAVA基础之一维数组和多维数组
    定位标记
    JSTL常用标签汇总
    struts1.2原理
    struts1.2中的ActionForm
    jdbc连接
    ActionForm与bean的区别
  • 原文地址:https://www.cnblogs.com/java20130725/p/3215836.html
Copyright © 2011-2022 走看看