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

  • 相关阅读:
    kendo ui 查找treelist里的子控件并设置是否显示的方法
    KendoUi下的DatePicker在谷歌浏览器上不能正常显示时间的解决方法
    asp.net 第三方UI控件 Telerik KendoUI 之 TreeVIew 的用法记录
    mysql批量更新数据,即:循环select记录然后更新某一字段
    Sql语句备份Sqlserver数据库
    3des用法示例,已测试
    制作Windows服务项目详细攻略
    利用好压在C#程序里实现RAR格式的压缩和解压功能
    winform里textBox无法获得焦点的解决方案
    Shell脚本批量重命名案例
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3196516.html
Copyright © 2011-2022 走看看