这篇文章中,我们将加入如何移动我们的坦克,以前的文章中,我们提到了一种虚拟摇杆,SneakInput。这里,我们将采用SneakInput类来作为我们的虚拟摇杆类。首页,我们新建一个控制层类,ControlLayer,这个类将管理着坦克的控制,OK,下面我们直接上代码:
ControlLayer.h
#include "cocos2d.h" #include "SneakyJoystick.h" #include "SneakyJoystickSkinnedBase.h" #include "MapLayer.h" #include "TankSprite.h" class ControlLayer: public cocos2d::CCLayer { public: virtual bool init(); // preprocessor macro for "static create()" constructor ( node() deprecated ) CREATE_FUNC(ControlLayer); MapLayer *_mapLayer; private: SneakyJoystick *joystick; void addJoystick(void); void update(float t); }; #endif /* defined(__TestTank2dx__ControlLayer__) */
ControlLayer.cpp
#include "ControlLayer.h" #include "SimpleAudioEngine.h" using namespace cocos2d; using namespace CocosDenshion; bool ControlLayer::init() { ////////////////////////////// if ( !CCLayer::init()) { return false; } this->addJoystick(); //调用系统的刷新函数 this->scheduleUpdate(); return true; } void ControlLayer::addJoystick() { float joystickRadius = 140; 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(); //背景 CCSprite *bgSprite=CCSprite::create("control_bg.png"); bgSprite->setOpacity(100); joystickSkin->setBackgroundSprite(bgSprite); //中心点 CCSprite *thumbSprite=CCSprite::create("cen.png"); thumbSprite->setOpacity(100); joystickSkin->setThumbSprite(thumbSprite); joystickSkin->getThumbSprite()->setScale(1.0f); joystickSkin->setPosition(CCPointMake(joystickRadius,joystickRadius)); joystickSkin->setJoystick(joystick); this->addChild(joystickSkin); } void ControlLayer::update(float t) { if (_mapLayer==NULL) { return; } TankSprite *tank=_mapLayer->_tank1; if (tank==NULL) { return; } // getVelocity()到的数值很小 需要放大 CCPoint poi = ccpMult(joystick->getVelocity(), 50); //right if ((poi.x > 0) && (poi.x - poi.y) >0 && (poi.x + poi.y) > 0){ tank->moveRight(); } //left else if ( (poi.x < 0) && (poi.x + poi.y) < 0 &&(poi.x - poi.y) < 0) { tank->moveLeft(); } //up else if ((poi.y > 0) &&(poi.y - poi.x) > 0 &&(poi.y + poi.x) >0 ){ tank->moveUp(); } //down else if ((poi.y < 0) &&(poi.y - poi.x) < 0 && (poi.y + poi.x) < 0) { tank->moveDown(); } }
TankSprite.cpp
void TankSprite::moveUp() { //设置旋转方向 this->setRotation(0); kaction=kUp; // CCPoint tp=this->getPosition(); this->setPosition(ccp(this->getPosition().x, this->getPosition().y+_speed)); } void TankSprite::moveDown() { } void TankSprite::moveLeft() { } void TankSprite::moveRight() { }
GameScene.cpp
_conLayer=ControlLayer::create(); _conLayer->_mapLayer=_mapLayer; this->addChild(_conLayer, 1);