根据上一篇内容进行改进
Control.h
CCSprite* main_tank; void control_update(float dt);
void Control::control_update(float dt) { float move_x=cen->getPositionX()-origin.x;//摇杆相对移动X轴 float move_y=cen->getPositionY()-origin.y;//摇杆相对移动y轴 if(isOnControl&&move_y!=0&&move_x!=0)//摇杆有移动时 { float ata=atan2(move_x,move_y);//换取遥感相对移动角度 ata=ata/M_PI;//角度数值化 //判断,确定方向 if(ata>-0.25&&ata<0.25) { main_tank->setRotation(0); main_tank->setPositionY(main_tank->getPositionY()+1); // CCLOG("top"); } if(ata>0.25&&ata<0.75) { main_tank->setRotation(90); main_tank->setPositionX(main_tank->getPositionX()+1); // CCLOG("right"); } if(ata>-0.75&&ata<-0.25) { main_tank->setRotation(270); main_tank->setPositionX(main_tank->getPositionX()-1); //CCLOG("left"); } if(ata>0.75||ata<-0.75) { main_tank->setRotation(180); main_tank->setPositionY(main_tank->getPositionY()-1); //CCLOG("down"); } // setTagPosition(main_tank->getPositionX(),main_tank->getPositionY()); } }
void Control::initData() { origin = ccp(150,150); //摇杆原点 control_bg = CCSprite::create("dpadUp.png"); control_bg->setPosition(origin); control_bg->setScale(2); this->addChild(control_bg); cen = CCSprite::create("joystickUp.png"); cen->setPosition(origin); this->addChild(cen); CCRect r = control_bg->boundingBox(); r_control = (r.getMaxX()-r.getMinX())/2; //摇杆半径 //---------------------- main_tank = CCSprite::create("an1_anim1.png"); main_tank->setPosition(ccp(50,50)); main_tank->setScale(0.5); this->addChild(main_tank); }
bool Control::ccTouchBegan(CCTouch* touch,CCEvent* event) { if (cen->boundingBox().containsPoint(touch->getLocation())) { isOnControl = true; cen->setScale(1.1); } //---------- schedule(schedule_selector(Control::control_update)); return true; }
void Control::ccTouchEnded(CCTouch* touch,CCEvent* event) { isOnControl = false; cen->setPosition(origin); cen->setScale(1); //--------- unscheduleAllSelectors(); }原文链接:https://www.f2er.com/cocos2dx/342564.html