SneakInput在cocos2d-x下的示例


看了很多教程和文档,无论2d还是2d-x都推荐使用开源的SneakInput作为其触屏的手柄组件。

因此我也下载了它的源码并将其融合到自己的游戏里,整个演示的源码下载地址为:

免费下载地址在 http://linux.bkjia.com/

用户名与密码都是www.bkjia.com

具体下载目录在 /2012年资料/8月/11日/SneakInput在cocos2d-x下的示例/

我的环境为vs2010 + cocos2d-1.0.1-x-0.12.0

另外SneakInput c++的源码下载地址为:https://github.com/Ntran013/SneakyInput

经过自己的试验,发现在我的环境下并不需要修改SneakInput的源码,将源码解压后,放在自己的项目里就可以正常使用。

SneakInput主要由2部分组成joystick和button。

使用button的代码:

  1. float buttonRadius=50;        
  2.   
  3. buttonA=new SneakyButton();  
  4. buttonA->autorelease();  
  5. buttonA->initWithRect(CCRectZero);  
  6. buttonA->setIsToggleable(false);  
  7. buttonA->setIsHoldable(true);          
  8.   
  9. SneakyButtonSkinnedBase *buttonASkin=new SneakyButtonSkinnedBase();  
  10. buttonASkin->autorelease();  
  11. buttonASkin->init();  
  12. buttonASkin->setPosition(ccp(size.width-buttonRadius,buttonRadius));  
  13. buttonASkin->setDefaultSprite(CCSprite::spriteWithFile("button-default.png"));  
  14. // buttonASkin->setDisabledSprite(CCSprite::spriteWithFile("button-disabled.png"));   
  15. buttonASkin->setPressSprite(CCSprite::spriteWithFile("button-pressed.png"));  
  16. buttonASkin->setActivatedSprite(CCSprite::spriteWithFile("button-activated.png"));  
  17. buttonASkin->setButton(buttonA);  
  18.   
  19. this->addChild(buttonASkin);  

使用jostick的代码:

  1. float joystickRadius=50;  
  2.   
  3. joystick=new SneakyJoystick();  
  4. joystick->autorelease();  
  5. joystick->initWithRect(CCRectZero);  
  6. joystick->setAutoCenter(true);  
  7. joystick->setHasDeadzone(true);  
  8. joystick->setDeadRadius(10);  
  9.   
  10. SneakyJoystickSkinnedBase *joystickSkin=new SneakyJoystickSkinnedBase();  
  11. joystickSkin->autorelease();  
  12. joystickSkin->init();  
  13. joystickSkin->setBackgroundSprite(CCSprite::spriteWithFile("button-disabled.png"));  
  14. joystickSkin->setThumbSprite(CCSprite::spriteWithFile("button-disabled.png"));  
  15. joystickSkin->getThumbSprite()->setScale(0.5f);  
  16. joystickSkin->setPosition(ccp(joystickRadius,joystickRadius));  
  17. joystickSkin->setJoystick(joystick);  
  18.   
  19. this->addChild(joystickSkin);  
然后在update函数中获取按钮状态:
  1. #define FIRE_INTERVAL 0.3f   
  2. float HelloWorld::fireTime=0;  
  3. void HelloWorld::update(ccTime dt)  
  4. {  
  5.     CCPoint velocity=joystick->getVelocity();  
  6.     if(velocity.x!=0||velocity.y!=0)  
  7.     {  
  8.         CCLOG("joystick:[%f,%f]",velocity.x,velocity.y);  
  9.     }  
  10.   
  11.     fireTime+=dt;  
  12.       
  13.     if(buttonA->getIsActive()&&fireTime>=FIRE_INTERVAL)  
  14.     {  
  15.         CCLOG("buttonA pressed.");  
  16.         fireTime=0;  
  17.     }  
  18. }  

相关内容