cocos2d-x的初步学习十三之虚拟摇杆SneakyInput

这篇文章中,我们将用另一个虚拟摇杆类,SneakyInput,这个是开源的,已经有c++版,SneakInput c++的源码下载地址为:https://github.com/Ntran013/SneakyInput

注意,这个下载下来需要修改,因为那是基于老版本的cocos2dx的。OK,我们下面直接上代码:

CCSize wsize=CCDirector::sharedDirector()->getVisibleSize();
    
    iconSprite=CCSprite::create("Icon-72.png");
    
    iconSprite->setPosition(ccp(wsize.width/2, wsize.height/2));
    iconSprite->setTag(123);
    
    this->addChild(iconSprite, 1);
    
    
    
   
    float joystickRadius = 220;

    
    joystick=new SneakyJoystick();
    joystick->autorelease();
    joystick->initWithRect(CCRectZero);
    //是否自动回到中心
    joystick->setAutoCenter(true);
    //是否支持死亡区域,该区域不会触发
    joystick->setHasDeadzone(true);
    //死亡区域半径
    joystick->setDeadRadius(10);
    
    SneakyJoystickSkinnedBase *joystickSkin=new SneakyJoystickSkinnedBase();
    joystickSkin->autorelease();
    joystickSkin->init();
    //背景
    joystickSkin->setBackgroundSprite(CCSprite::create("control_bg.png"));
    //中心点
    joystickSkin->setThumbSprite(CCSprite::create("cen.png"));
    joystickSkin->getThumbSprite()->setScale(1.0f);
    joystickSkin->setPosition(CCPointMake(joystickRadius,joystickRadius));
    joystickSkin->setJoystick(joystick);
    
    this->addChild(joystickSkin);
   

    this->scheduleUpdate();


//刷新
void HelloWorld::update(float t)
{


    //  getVelocity()到的数值很小 需要放大 
    CCPoint poi = ccpMult(joystick->getVelocity(), 50);
    
    
    
    //right
    if ((poi.x  >  0)  && (poi.x - poi.y) >0 && (poi.x + poi.y) > 0){
        
        
        
        iconSprite->setPosition(ccp(iconSprite->getPosition().x+1, iconSprite->getPosition().y));
        
        
        
    }
    //left
    else if ( (poi.x < 0)  && (poi.x + poi.y) < 0 &&(poi.x - poi.y) < 0) {
        

        iconSprite->setPosition(ccp(iconSprite->getPosition().x-1, iconSprite->getPosition().y));

        
    }
    //up
    else if ((poi.y > 0) &&(poi.y - poi.x) > 0 &&(poi.y + poi.x) >0 ){
        

        iconSprite->setPosition(ccp(iconSprite->getPosition().x, iconSprite->getPosition().y+1));

        
        
    }
    //down
    else if ((poi.y < 0) &&(poi.y - poi.x) < 0 && (poi.y + poi.x) < 0) {
        
    
        iconSprite->setPosition(ccp(iconSprite->getPosition().x, iconSprite->getPosition().y-1));


    }



}


在上面中,我们初始化了一个精灵,并且初始化了 SneakyInput,然后再刷新函数里,我们去判断摇杆方向,然后移动精灵。OK,我们看下效果:

cocos2d-x的初步学习十三之虚拟摇杆SneakyInput_第1张图片


OK,就这么简单呐±±±±~~~~~

你可能感兴趣的:(游戏,cocos2d,cocos2d-x,摇杆,SneakyInput)