void GameScene_Box2D::initPhysics() { b2Vec2 gravity = b2Vec2(0, -9.8); //重力を作成 _world = new b2World(gravity); //Worldを作成 b2DestructionListener *listener; _world->SetDestructionListener(listener); // _world->SetDestructionListener(this); _debugDraw = new GLESDebugDraw( PTM_RATIO ); _world->SetDebugDraw(_debugDraw); const b2ParticleSystemDef particleSystemDef; //particleSystemDef->flags = b2_waterParticle; _particleSystem = _world->CreateParticleSystem(&particleSystemDef); //_particleSystem->SetRadius(50/PTM_RATIO); b2ParticleGroupDef groupDef; //groupDef.flags = b2_waterParticle; _particleGroup = _particleSystem->CreateParticleGroup(groupDef); uint32 flags = 0; flags += b2Draw::e_shapeBit; //flags += b2Draw::e_particleBit; // flags += b2Draw::e_jointBit; // flags += b2Draw::e_aabbBit; // flags += b2Draw::e_pairBit; // flags += b2Draw::e_centerOfMassBit; _debugDraw->SetFlags(flags); //画面サイズサイズを取得 auto window_size = Director::getInstance()->getWinSize(); //床 auto floor = cocos2d::extension::PhysicsSprite::create(); floor->setTextureRect(Rect(0,0,window_size.width,100)); _floor = floor->getSpriteFrame()->getRect(); auto size = floor->getContentSize(); b2BodyDef bodyDef; bodyDef.type = b2_staticBody; bodyDef.position.Set(0, -size.height/PTM_RATIO); b2Body *body = _world->CreateBody(&bodyDef); b2PolygonShape dynamicBox; dynamicBox.SetAsBox(size.width/PTM_RATIO, size.height/PTM_RATIO); b2FixtureDef fixtureDef; fixtureDef.shape = &dynamicBox; fixtureDef.density = 1.0f; body->CreateFixture(&fixtureDef); floor->setColor(Color3B(255,255,255)); floor->setTag(spriteType::kFloor); // addChild(floor); auto left_wall = cocos2d::extension::PhysicsSprite::create(); left_wall->setTextureRect(Rect(10,window_size.height/2,10,window_size.height*2)); //left_wall->setPosition(Vec2(10, window_size.height/2)); left_wall->setColor(Color3B(255,255,255)); _leftwall = left_wall->getSpriteFrame()->getRect(); bodyDef.type = b2_staticBody; bodyDef.position.Set(0, 0); b2Body *bodyleft = _world->CreateBody(&bodyDef); b2PolygonShape dynamicBoxleft; dynamicBoxleft.SetAsBox(10/PTM_RATIO, window_size.height*2/PTM_RATIO); b2FixtureDef fixtureDefleft; fixtureDefleft.shape = &dynamicBoxleft; fixtureDefleft.density = 1.0f; bodyleft->CreateFixture(&fixtureDefleft); auto right_wall = cocos2d::extension::PhysicsSprite::create(); right_wall->setTextureRect(Rect(window_size.width,window_size.height/2,10,window_size.height*2)); size = right_wall->getContentSize(); bodyDef.type = b2_staticBody; bodyDef.position.Set(window_size.width/PTM_RATIO, 0); b2Body *bodyright_wall = _world->CreateBody(&bodyDef); b2PolygonShape dynamicBoxright_wall; dynamicBoxright_wall.SetAsBox(10/PTM_RATIO, window_size.height*2/PTM_RATIO); b2FixtureDef fixtureDefright; fixtureDefright.shape = &dynamicBoxright_wall; fixtureDefright.density = 1.0f; bodyright_wall->CreateFixture(&fixtureDefright); right_wall->setColor(Color3B(255,255,255)); _rightwall = right_wall->getSpriteFrame()->getRect(); //addChild(right_wall); _ceil = Rect(window_size.width/2, window_size.height - 200, window_size.width, 100); }
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 , origin.y + closeItem->getContentSize().height/2)); // create menu, it's an autorelease object auto menu = Menu::create(closeItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); ///////////////////////////// // 3. add your codes below... // add a label shows "Hello World" // create and initialize a label string testReport; int exitCode = PlayFabApiTest::HackishManualTestExecutor(); auto label = Label::createWithTTF(PlayFabApiTest::GetTestReport(), "fonts/Marker Felt.ttf", 24); // position the label on the center of the screen label->setPosition(Vec2(origin.x + visibleSize.width/2, origin.y + visibleSize.height - label->getContentSize().height)); // add the label as a child to this layer this->addChild(label, 1); // add "HelloWorld" splash screen" auto sprite = Sprite::create("HelloWorld.png"); // position the sprite on the center of the screen sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); // add the sprite as a child to this layer this->addChild(sprite, 0); if (HelloWorld::cmdLine.find("-exit") != string::npos) exit(exitCode); return true; }
bool GameOverLayer::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); //bg auto bg = TMXTiledMap::create("map/blue_bg.tmx"); this->addChild(bg); //eff ParticleSystem *ps = ParticleSystemQuad::create("particle/light.plist"); ps->setPosition(Vec2(visibleSize.width, visibleSize.height - 200) / 2); this->addChild(ps); auto top = Sprite::createWithSpriteFrameName("gameover.top.png"); //top top->setAnchorPoint(Vec2(0,0)); top->setPosition(Vec2(0, visibleSize.height - top->getContentSize().height)); this->addChild(top); UserDefault *defaults = UserDefault::getInstance(); int highScore = defaults->getIntegerForKey(HIGHSCORE_KEY); if (highScore < score) { highScore = score; defaults->setIntegerForKey(HIGHSCORE_KEY,highScore); } __String *text = __String::createWithFormat("%i points", highScore); auto lblHighScore = Label::createWithTTF(HellcUtils::getUTF8Char("lblHighScore"), "fonts/hanyi.ttf", 25); lblHighScore->setAnchorPoint(Vec2(0,0)); lblHighScore->setPosition(Vec2(60, top->getPosition().y - 30)); addChild(lblHighScore); auto lblScore = Label::createWithTTF(text->getCString(), "fonts/hanyi.ttf", 24); lblScore->setColor(Color3B(75,255,255)); lblScore->setAnchorPoint(Vec2(0,0)); lblScore->setPosition(lblHighScore->getPosition() - Vec2(0, 40)); addChild(lblScore); auto text2 = Label::createWithTTF("Tap the Screen to Play", "fonts/hanyi.ttf", 24); text2->setAnchorPoint(Vec2(0,0)); text2->setPosition(lblScore->getPosition() - Vec2(10, 45)); addChild(text2); //touch auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = [](Touch* touch, Event* event){ Director::getInstance()->popScene(); if (UserDefault::getInstance()->getBoolForKey(SOUND_KEY)) { SimpleAudioEngine::getInstance()->playEffect(sound_1); } return false; }; //touch EventDispatcher* eventDispatcher = Director::getInstance()->getEventDispatcher(); eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); return true; }
// on "init" you need to initialize your instance bool SceneLocalization::init() { ////////////////////////////// // 1. super init first if (!SceneBase::init()) { return false; } cocos2d::Size windowSize = Director::getInstance()->getWinSize(); #if defined(AK_ANDROID) || defined(AK_IOS) float descriptionPosX = windowSize.width * 0.50f; float descriptionPosY = windowSize.height * 0.90f; float selectButtonPosX = windowSize.height * 0.50f; #else float descriptionPosX = windowSize.width * 0.50f; float descriptionPosY = windowSize.height * 0.90f; float selectButtonPosX = windowSize.width * 0.15f; #endif // AK_ANDROID ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. { //addLabel("Localization Demos Menu", descriptionPosX, descriptionPosY, 30); int y = descriptionPosY; // Add button linking to the Say "Hello" { auto selectItem = MenuItemImage::create("PlayNormal.png", "PlayPush.png", CC_CALLBACK_1(SceneLocalization::onSayHello, this)); y -= selectItem->getContentSize().height; addItem(selectItem, selectButtonPosX, y, this); addLabelEx("Say \"Hello\"", selectItem->getPosition().x + selectItem->getContentSize().width, selectItem->getPosition().y, FONT_SIZE_MENU, this, CC_CALLBACK_1(SceneLocalization::onSayHello, this)); } // Add button linking to RTPC Demo (Car Engine) { auto selectItem = MenuItemImage::create("PlayNormal.png", "PlayPush.png", CC_CALLBACK_1(SceneLocalization::onLanguageChanged, this)); y -= selectItem->getContentSize().height; addItem(selectItem, selectButtonPosX, y, this); cocos2d::MenuItemLabel* pMenu = addLabelEx("Language:English(US)", selectItem->getPosition().x + selectItem->getContentSize().width, selectItem->getPosition().y, FONT_SIZE_MENU, this, CC_CALLBACK_1(SceneLocalization::onLanguageChanged, this)); m_language = (Label*)pMenu->getChildren().at(0); } } // Load the sound bank AkBankID bankID; // Not used if (AK::SoundEngine::LoadBank("Human.bnk", AK_DEFAULT_POOL_ID, bankID) != AK_Success) { SetErrorMessage("Human.bnk"); return false; } LOGAK("<SceneLocalization::init>3"); // Register the "Human" game object AK::SoundEngine::RegisterGameObj(GAME_OBJECT_HUMAN, "Human"); scheduleUpdate(); return true; }
bool MainMenuScene::init() { ////////////////////////////// // 1. super init first if (!Layer::init()) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. Vector<MenuItem*> MenuItems; // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(MainMenuScene::menuCloseCallback, this)); closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width / 2, origin.y + closeItem->getContentSize().height / 2)); //http://www.cocos2d-x.org/programmersguide/6/#menu-and-menu-items auto startItem = MenuItemImage::create( "startButton.png", "startButtonSelected.png", CC_CALLBACK_1(MainMenuScene::startGame, this)); startItem->setPosition(Vec2(startItem->getContentSize().width,startItem->getContentSize().height)); MenuItems.pushBack(closeItem); MenuItems.pushBack(startItem); // create menu, it's an autorelease object auto menu = Menu::createWithArray(MenuItems); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); std::string pNormalSprite = "green_edit.png"; Size editBoxSize = Size(100, 20); this->_editPlayers = ui::EditBox::create(editBoxSize, ui::Scale9Sprite::create(pNormalSprite)); _editPlayers->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height * 3 / 4)); _editPlayers->setFontName("fonts/arial.ttf"); _editPlayers->setFontSize(12); _editPlayers->setFontColor(Color3B::RED); _editPlayers->setText("# of Players"); _editPlayers->setPlaceholderFontColor(Color3B::WHITE); //_editPlayers->setInputMode(ui::EditBox::InputMode::NUMERIC); _editPlayers->setMaxLength(3); _editPlayers->setReturnType(ui::EditBox::KeyboardReturnType::DONE); this->addChild(this->_editPlayers); _editPlayers->setDelegate(this); ///////////////////////////// // 3. add your codes below... // create and initialize a label auto label = Label::createWithTTF("Press P or click Start to begin", "fonts/Marker Felt.ttf", 24); // position the label on the center of the screen label->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - label->getContentSize().height)); // add the label as a child to this layer this->addChild(label, 1); // add "HelloWorld" splash screen" auto sprite = Sprite::create("HelloWorld.png"); // position the sprite on the center of the screen sprite->setPosition(Vec2(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y - 30)); // add the sprite as a child to this layer this->addChild(sprite, 0); //creating touch listener to wait for P key to be pressed auto listener = EventListenerKeyboard::create(); listener->onKeyReleased = CC_CALLBACK_2(MainMenuScene::onKeyReleased, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); return true; }
void UI::createIngameUI() { m_pIngame->removeAllChildren(); m_playerMuni = nullptr; Size visibleSize = Director::getInstance()->getVisibleSize(); //################################################ m_pPlayer = pHelloWorld->getPlayer(); lastLife = m_pPlayer->getHealth(); m_pPlayerLife = new Sprite*[3]; for (int i = 0; i < 3; ++i) { std::string str = std::string("Resources/GUI/life"); str.append(std::to_string(i + 1)); str.append(".png"); m_pPlayerLife[i] = Sprite::create(str); m_pPlayerLife[i]->setPosition( 135.0f + m_pPlayerLife[i]->getContentSize().width * 0.5f, 95.0f + m_pPlayerLife[i]->getContentSize().height * 0.5f); m_pPlayerLife[i]->setVisible((lastLife - 1) == i); m_pIngame->addChild(m_pPlayerLife[i], 2); } lastCrystal = CollectibleCrystal::getCrystalCount(); m_pCrystals = new Sprite*[4]; for (int i = 0; i < 4; ++i) { std::string str = std::string("Resources/GUI/"); str.append(std::to_string(i + 1)); str.append(".png"); m_pCrystals[i] = Sprite::create(str); m_pCrystals[i]->setPosition( 202.0f + m_pCrystals[i]->getContentSize().width * 0.5f, 42.0f + m_pCrystals[i]->getContentSize().height * 0.5f); m_pCrystals[i]->setVisible((lastCrystal - 1) == i); m_pIngame->addChild(m_pCrystals[i], 2); } m_polle = Sprite::create("Resources/GUI/holybell.png"); m_polle->setPosition(270.0f, 66.0f); m_polle->setVisible(lastCrystal > 0); m_crystal = Sprite::create("Resources/GUI/crystall.png"); m_crystal->setPosition(175.0f, 61.0f); m_crystal->setVisible(lastCrystal > 0); m_pGameOver = LabelTTF::create("GAME OVER", "Resources/fonts/Comic Book.ttf", 64); m_pGameOver->setPosition(visibleSize.width * 0.5f, visibleSize.height * 0.5f); m_pGameOver->setVisible(false); lastMuni = m_pPlayer->getNuts(); createMuniLabel(); Sprite* bg = Sprite::create("Resources/GUI/bg.png"); bg->setPosition( 5 + bg->getContentSize().width * 0.5f, 5 + bg->getContentSize().height *0.5f); m_pIngame->addChild(m_polle, 2); m_pIngame->addChild(m_crystal, 2); m_pIngame->addChild(bg, 1); //################################################ auto closeItem = MenuItemImage::create( "Resources/pictures/generic/CloseNormal.png", "Resources/pictures/generic/CloseSelected.png", CC_CALLBACK_1(MainLayer::menuCloseCallback, pHelloWorld)); closeItem->setScale(2.0f); closeItem->setPosition( visibleSize.width - closeItem->getScaleX() * closeItem->getContentSize().width * 0.5f, closeItem->getScaleY() * closeItem->getContentSize().height * 0.5f); // create menu, it's an autorelease object auto menu = Menu::create(closeItem, NULL); menu->setPosition(Point::ZERO); m_pIngame->addChild(menu, 1); m_pIngame->addChild(m_pGameOver, 9999); }
//////////////////////////////////////////////////// // Checks if the point is contained inside this node //////////////////////////////////////////////////// bool GameObject::containsPoint( cocos2d::CCPoint location ) { location = convertToNodeSpace(location); CCRect rect = CCRect(0,0, getContentSize().width, getContentSize().height); return CCRect::CCRectContainsPoint(rect, location); }
bool OptionScene::init() { if (!Scene::init()) return false; Size visibleSize = Director::getInstance()->getVisibleSize(); //--·µ»Ø°´Å¥--// auto exitScene = [](Ref* pSender) { Director::getInstance()->replaceScene(TransitionFlipX::create(0.5f, MainScene::create(), TransitionScene::Orientation::LEFT_OVER)); }; auto backItem = MenuItemImage::create("UI/BackNormal.png", "UI/BackSelected.png", exitScene); backItem->setPosition(Vec2(backItem->getContentSize().width / 2 + 10, visibleSize.height - backItem->getContentSize().height / 2 - 10)); auto backMenu = Menu::create(backItem, NULL); backMenu->setPosition(Vec2::ZERO); this->addChild(backMenu); //--¸ù²Ëµ¥--// auto rootLayout = createLayout(Lang::get("optionTitle"), this->getContentSize()); this->addChild(rootLayout); auto list = ListView::create(); list->setDirection(ScrollView::Direction::VERTICAL); list->setGravity(ListView::Gravity::CENTER_HORIZONTAL); list->setBounceEnabled(true); list->setItemsMargin(10); list->setContentSize(Size(700, 480)); list->setAnchorPoint(Vec2(0.5f, 0.5f)); list->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2 - 20)); rootLayout->addChild(list); //--ÓïÑÔ°´Å¥--// auto langButton = createButton(Lang::get("selectLang"), Size(600, 60), [=](Ref* pSender) { auto button = (Button*)pSender; auto langLayout = createLayout(Lang::get("selectLang"), Size(600, 600)); auto langList = ListView::create(); langList->setDirection(ScrollView::Direction::VERTICAL); langList->setItemsMargin(10); langList->setGravity(ListView::Gravity::CENTER_HORIZONTAL); langList->setBounceEnabled(true); langList->setContentSize(Size(600, 480)); langList->setAnchorPoint(Vec2(0.5f, 0.5f)); langList->setPosition(Vec2(langLayout->getContentSize().width / 2, langLayout->getContentSize().height / 2 - 20)); langLayout->addChild(langList); auto langs = Lang::getAllLangs(); auto autoLangButton = createButton(Lang::get("autoLang"), Size(500, 60), [this](Ref* pSender) { auto button = static_cast<Button*> (pSender); highlightingButton->loadTextureNormal("UI/ButtonNormal.png"); highlightingButton->setContentSize(Size(500, 60)); highlightingButton = button; button->loadTextureNormal("UI/ButtonActive.png"); button->setContentSize(Size(500, 60)); Lang::setAutoLang(true); Lang::loadAutoLang(); }); if (Lang::isAutoLang()) { autoLangButton->loadTextureNormal("UI/ButtonActive.png"); autoLangButton->setContentSize(Size(500, 60)); highlightingButton = autoLangButton; } langList->addChild(autoLangButton); for (auto i : langs) { auto langButton = createButton(i.first, Size(500, 60), [i, this](Ref* pSender) { auto button = static_cast<Button*> (pSender); highlightingButton->loadTextureNormal("UI/ButtonNormal.png"); highlightingButton->setContentSize(Size(500, 60)); highlightingButton = button; button->loadTextureNormal("UI/ButtonActive.png"); button->setContentSize(Size(500, 60)); Lang::setAutoLang(false); Lang::loadLang(i.second); }); if (!Lang::isAutoLang() && i.second == Lang::getCurrentLang()) { langButton->loadTextureNormal("UI/ButtonActive.png"); langButton->setContentSize(Size(500, 60)); highlightingButton = langButton; } langList->addChild(langButton); } goInto(rootLayout, button, langLayout); backItem->setCallback([=](Ref* pSender) { goOut(rootLayout, button, langLayout); backItem->setCallback(exitScene); }); }); list->addChild(langButton); return true; }
// on "init" you need to initialize your instance bool Sprite3DLesson5::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(Sprite3DLesson5::menuCloseCallback, this)); closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 , origin.y + closeItem->getContentSize().height/2)); // create menu, it's an autorelease object auto menu = Menu::create(closeItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesEnded = CC_CALLBACK_2(Sprite3DLesson5::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); ///////////////////////////// std::string filename = "res/Sprite3D/girl.c3b"; auto sprite = Sprite3D::create(filename); sprite->setPosition(visibleSize.width/2 + origin.x, visibleSize.height/3 + origin.y); addChild(sprite); auto animation = Animation3D::create(filename); auto animate = Animate3D::create(animation); sprite->runAction(RepeatForever::create(animate)); auto lfoot = Sprite::create("res/Sprite3D/circle.png"); auto rfoot = Sprite::create("res/Sprite3D/circle.png"); _lfoot = Sprite3D::create(); _lfoot->addChild(lfoot); _lfoot->setRotation3D(Vec3(90, 0, 0)); _rfoot = Sprite3D::create(); _rfoot->addChild(rfoot); _rfoot->setRotation3D(Vec3(90, 0, 0)); addChild(_lfoot); addChild(_rfoot); _lfoot->setScale(0.3f); _rfoot->setScale(0.3f); _lfoot->setVisible(false); _rfoot->setVisible(false); _sprite = sprite; ValueMap valuemap0; valuemap0["footname"] = Value("Bip001 R Toe0"); valuemap0["lfoot"] = Value(false); animate->setKeyFrameUserInfo(10, valuemap0); valuemap0["footname"] = Value("Bip001 L Toe0"); valuemap0["lfoot"] = Value(true); animate->setKeyFrameUserInfo(26, valuemap0); auto listener2 = EventListenerCustom::create(Animate3DDisplayedNotification, [&](EventCustom* event) { auto info = (Animate3D::Animate3DDisplayedEventInfo*)event->getUserData(); auto footname = info->userInfo->at("footname").asString(); bool lfoot = info->userInfo->at("lfoot").asBool(); auto mat = _sprite->getNodeToWorldTransform() * _sprite->getSkeleton()->getBoneByName(footname)->getWorldMat(); Sprite3D* foot = lfoot ? _lfoot : _rfoot; foot->setPosition3D(Vec3(mat.m[12], mat.m[13], mat.m[14])); foot->setVisible(true); cocos2d::log("frame %d", info->frame); }); Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(listener2, -1); scheduleUpdate(); return true; }
bool Failed::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(Failed::menuCloseCallback, this)); closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 , origin.y + closeItem->getContentSize().height/2)); // create menu, it's an autorelease object auto menu = Menu::create(closeItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); ///////////////////////////// // 3. add your codes below... // add a label shows "Hello World" // create and initialize a label auto label = LabelTTF::create("", "Arial", 24); // position the label on the center of the screen label->setPosition(Vec2(origin.x + visibleSize.width/2, origin.y + visibleSize.height - label->getContentSize().height)); // add the label as a child to this layer this->addChild(label, 1); // add "GamePlaying" splash screen" auto sprite = Sprite::create("failed.png"); // position the sprite on the center of the screen sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); // add the sprite as a child to this layer this->addChild(sprite, 0); //_camera = new ActionCamera; //_camera->startWithTarget(menu); auto dispacher = Director::getInstance()->getEventDispatcher(); auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = CC_CALLBACK_2(Failed::onTouchBegan,this); listener->onTouchMoved = CC_CALLBACK_2(Failed::onTouchMoved,this); dispacher->addEventListenerWithSceneGraphPriority(listener,this); Director::getInstance()->setProjection(Director::Projection::_2D); scheduleUpdate(); runAction( Repeat::create( Sequence::create( Place::create(Vec2(0,-8)), DelayTime::create(0.1f), Place::create(Vec2(0,0)), DelayTime::create(0.1f), nullptr), 3) ); return true; }
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if (!Layer::init()) { return false; } auto visibleSize = Director::getInstance()->getVisibleSize(); auto origin = Director::getInstance()->getVisibleOrigin(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create("CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback,this)); closeItem->setPosition( origin + Vec2(visibleSize) - Vec2(closeItem->getContentSize() / 2)); // create menu, it's an autorelease object auto menu = Menu::create(closeItem, nullptr); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); ///////////////////////////// // 3. add your codes below... // add a label shows "Hello World" // create and initialize a label auto label = LabelTTF::create("Hello World", "Arial", TITLE_FONT_SIZE); // position the label on the center of the screen label->setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - label->getContentSize().height); // add the label as a child to this layer this->addChild(label, 1); { { // 注册物理碰撞事件监听 auto listener = EventListenerPhysicsContact::create(); listener->onContactBegin = [this](PhysicsContact& contact) { log("onContactBegin"); auto spriteA = (Sprite*)contact.getShapeA()->getBody()->getNode(); auto spriteB = (Sprite*)contact.getShapeB()->getBody()->getNode(); return true; }; listener->onContactPreSolve = [] (PhysicsContact& contact, PhysicsContactPreSolve& solve) { // log("onContactPreSolve"); return true; }; listener->onContactPostSolve = [] (PhysicsContact& contact, const PhysicsContactPostSolve& solve) { // log("onContactPostSolve"); }; listener->onContactSeperate = [](PhysicsContact& contact) { log("onContactSeperate"); }; Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority( listener, 1); } { // touch event监听 auto touchListener = EventListenerTouchOneByOne::create(); touchListener->setSwallowTouches(true); touchListener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan, this); touchListener->onTouchMoved = CC_CALLBACK_2(HelloWorld::onTouchMoved, this); touchListener->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded, this); Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(touchListener, this); } } return true; }
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 , origin.y + closeItem->getContentSize().height/2)); // create menu, it's an autorelease object auto menu = Menu::create(closeItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); ///////////////////////////// // 3. add your codes below... // add a label shows "Hello World" // create and initialize a label label = Label::create("Hello World", "Arial", 24); // position the label on the center of the screen label->setPosition(Vec2(origin.x + visibleSize.width/2, origin.y + visibleSize.height - label->getContentSize().height)); // add the label as a child to this layer this->addChild(label, 1); // add "HelloWorld" splash screen" auto sprite = Sprite::create("HelloWorld.png"); // position the sprite on the center of the screen sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); // add the sprite as a child to this layer this->addChild(sprite, 0); /********************************************************************************** SSアニメ表示のサンプルコード Visual Studio Express 2013 for Windows Desktopで動作を確認しています。 ssbpとpngがあれば再生する事ができますが、Resourcesフォルダにsspjも含まれています。 **********************************************************************************/ //-------------------------------------------------------------------------------- //SS5.5から搭載されたエフェクト機能の最適化を行いSS5Managerクラスが追加されました。 //プレイヤーが共有するエフェクトバッファを作成します。 //バッファは常駐されますのでゲーム起動時等に1度行ってください。 auto ss5man = ss::SS5Manager::getInstance(); ss5man->createEffectBuffer(1024); //エフェクト用バッファの作成 //-------------------------------------------------------------------------------- //リソースマネージャの作成 auto resman = ss::ResourceManager::getInstance(); //プレイヤーの作成 ssplayer = ss::Player::create(); //アニメデータをリソースに追加 //それぞれのプラットフォームに合わせたパスへ変更してください。 resman->addData("OPTPiX_SpriteStudio_ParticleEffectSample_150813\\effect_sample.ssbp"); //プレイヤーにリソースを割り当て ssplayer->setData("effect_sample"); // ssbpファイル名(拡張子不要) //再生するモーションを設定 ssplayer->play("e006/sengeki"); // アニメーション名を指定(ssae名/アニメーション名) //アニメの位置を設定 ssplayer->setPosition(visibleSize.width / 2, visibleSize.height / 2); //スケールの変更 ssplayer->setScale(1.0f, 1.0f); //ユーザーデータコールバックを設定 ssplayer->setUserDataCallback(CC_CALLBACK_2(HelloWorld::userDataCallback, this)); //アニメーション終了コールバックを設定 ssplayer->setPlayEndCallback(CC_CALLBACK_1(HelloWorld::playEndCallback, this)); //プレイヤーをゲームシーンに追加 this->addChild(ssplayer, 10); //updeteの作成 this->scheduleUpdate(); return true; }
void EditorMenuManager::createItems() { Rect rect = VisibleRect::getVisibleRect(); this->setZOrder(2); auto scene = dynamic_cast<GameLogic*>(this->getParent()); if (scene) { /*--------------------- Input Menu -------------------------*/ auto player = scene->getPlayer(); if (player) { auto inputMenu = InputMenuItem::create(); inputMenu->setPosition(0, rect.getMaxY()); inputMenu->setPlayer(player); inputMenu->initLevelVar(); this->addChild(inputMenu, 0, INPUT_MENU); auto inputMenuSize = inputMenu->getContentSize(); auto inputTabLayer = LayerColor::create(Color4B(50,50,50,200), inputMenuSize.width / 17, inputMenuSize.height / 3); inputTabLayer->setPosition(0, -(inputMenuSize.height / 3)); inputMenu->addChild(inputTabLayer, 0, 1); Sprite* inputTabSprite = Sprite::create("Pan_Tab.png"); inputTabSprite->setScale(0.6f, 0.6f); MenuItemSprite* inputTabItem = MenuItemSprite::create(inputTabSprite, inputTabSprite, inputTabSprite, CC_CALLBACK_1(EditorMenuManager::inputTabPressed, this)); Menu *inputTab = Menu::create(inputTabItem, NULL); inputTab->setPosition(44, 48); inputTabLayer->addChild(inputTab, 0, 1); } /*--------------------- Sheep Menu -------------------------*/ __Array* sheepArray = scene->getSheep(); if (sheepArray->count() > 0) { auto sheepMenu = SheepMenuItem::create(); sheepMenu->setPosition(0, rect.getMaxY()); sheepMenu->setScene(scene); sheepMenu->initLevelVar(); this->addChild(sheepMenu, 0, SHEEP_MENU); auto sheepMenuSize = sheepMenu->getContentSize(); auto sheepTabLayer = LayerColor::create(Color4B(50,50,50,200), sheepMenuSize.width / 17, sheepMenuSize.height / 3); sheepTabLayer->setPosition(sheepMenuSize.width / 17, -(sheepMenuSize.height / 3)); sheepMenu->addChild(sheepTabLayer, 0, 1); Sprite* sheepTabSprite = Sprite::create("Pecora_Tab.png"); sheepTabSprite->setScale(0.8f, 0.8f); MenuItemSprite* sheepTabItem = MenuItemSprite::create(sheepTabSprite, sheepTabSprite, sheepTabSprite, CC_CALLBACK_1(EditorMenuManager::sheepTabPressed, this)); Menu *sheepTab = Menu::create(sheepTabItem, NULL); sheepTab->setPosition(34, 34); sheepTabLayer->addChild(sheepTab, 0, 2); } /*--------------------- Note Menu --------------------------*/ if (player && (sheepArray->count() >0)) { auto noteMenu = NoteMenuItem::create(); noteMenu->setPosition(0, rect.getMaxY()); noteMenu->setPlayer(player); noteMenu->setScene(scene); noteMenu->initLevelVar(); this->addChild(noteMenu, 0, NOTE_MENU); auto noteMenuSize = noteMenu->getContentSize(); auto noteTabLayer = LayerColor::create(Color4B(50,50,50,200), noteMenuSize.width / 17, noteMenuSize.height / 3); noteTabLayer->setPosition(noteMenuSize.width / 8.5, -(noteMenuSize.height / 3)); noteMenu->addChild(noteTabLayer, 0, 1); Sprite* noteTabSprite = Sprite::create("Nota_Tab.png"); noteTabSprite->setScale(0.8f, 0.8f); MenuItemSprite* noteTabItem = MenuItemSprite::create(noteTabSprite, noteTabSprite, noteTabSprite, CC_CALLBACK_1(EditorMenuManager::noteTabPressed, this)); Menu *noteTab = Menu::create(noteTabItem, NULL); noteTab->setPosition(34, 34); noteTabLayer->addChild(noteTab, 0, 3); } /*--------------------- Goatskin Menu --------------------------*/ __Array* goatskinArray = scene->getGoatskins(); if (goatskinArray->count() > 0) { auto goatskinMenu = GoatskinMenuItem::create(); goatskinMenu->setPosition(0, rect.getMaxY()); goatskinMenu->setScene(scene); goatskinMenu->initLevelVar(); this->addChild(goatskinMenu, 0, GOATSKIN_MENU); auto goatskinMenuSize = goatskinMenu->getContentSize(); auto goatskinTabLayer = LayerColor::create(Color4B(50,50,50,200), goatskinMenuSize.width / 17, goatskinMenuSize.height / 3); goatskinTabLayer->setPosition(goatskinMenuSize.width / 5.67, -(goatskinMenuSize.height / 3)); goatskinMenu->addChild(goatskinTabLayer, 0, 1); Sprite* goatskinTabSprite = Sprite::create("rock_2x2.png"); goatskinTabSprite->setScale(0.3f, 0.3f); MenuItemSprite* goatskinTabItem = MenuItemSprite::create(goatskinTabSprite, goatskinTabSprite, goatskinTabSprite, CC_CALLBACK_1(EditorMenuManager::goatskinTabPressed, this)); Menu *goatskinTab = Menu::create(goatskinTabItem, NULL); goatskinTab->setPosition(74, 70); goatskinTabLayer->addChild(goatskinTab, 0, 4); } } /*----------------- Save Data selection --------------------*/ auto saveTabLayer = LayerColor::create(Color4B(50,50,50,200), rect.getMaxX() / 17, rect.getMaxY() / 12); saveTabLayer->setPosition((rect.getMaxX() - (rect.getMaxX() / 8.5)), (rect.getMaxY() - (rect.getMaxY() / 12))); this->addChild(saveTabLayer, 0, SAVE); auto saveLabel = Label::createWithSystemFont("SAVE", "Marker Felt", 15); MenuItemLabel* saveTabItem = MenuItemLabel::create(saveLabel, CC_CALLBACK_1(EditorMenuManager::saveTabPressed, this)); Menu *saveTab = Menu::create(saveTabItem, NULL); saveTab->setPosition(28, 26); saveTabLayer->addChild(saveTab, 0, 1); /*--------------- Back to Level selection ------------------*/ auto backTabLayer = LayerColor::create(Color4B(50,50,50,200), rect.getMaxX() / 17, rect.getMaxY() / 12); backTabLayer->setPosition((rect.getMaxX() - (rect.getMaxX() / 17)), (rect.getMaxY() - (rect.getMaxY() / 12))); this->addChild(backTabLayer, 0, BACK); auto backLabel = Label::createWithSystemFont("BACK", "Marker Felt", 15); MenuItemLabel* backTabItem = MenuItemLabel::create(backLabel, CC_CALLBACK_1(EditorMenuManager::backTabPressed, this)); Menu *backTab = Menu::create(backTabItem, NULL); backTab->setPosition(28, 26); backTabLayer->addChild(backTab, 0, 1); }
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); auto bg = Sprite::create("HelloWorld.png"); bg->setScale(this->getContentSize().width / bg->getContentSize().width, this->getContentSize().height / bg->getContentSize().height); bg->setColor(Color3B::ORANGE); bg->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT); addChild(bg); m_gameLy = Layer::create(); m_gameLy->setContentSize(Size(visibleSize.width, visibleSize.height * 4)); addChild(m_gameLy, 1); m_hubLy = HubLayer::create(); m_hubLy->setContentSize(Size(visibleSize.width * 0.25, visibleSize.height * 4 * 0.15)); m_hubLy->setPosition(Vec2(1, (this->getContentSize().height - m_hubLy->getContentSize().height) / 2)); addChild(m_hubLy, 1); m_hubLy->setgLayer(m_gameLy); auto lD = LayerColor::create(Color4B(255.0, 0, 0, 255.0), visibleSize.width, 30); lD->setTag(10); lD->setPosition(Vec2(0, m_gameLy->getContentSize().height - lD->getContentSize().height)); m_gameLy->addChild(lD); auto lP = LayerColor::create(Color4B(0, 255.0, 0, 255.0), visibleSize.width, 30); m_gameLy->addChild(lP); lP->setTag(11); auto dispatcher = Director::getInstance()->getEventDispatcher(); auto touchListener = EventListenerTouchOneByOne::create(); touchListener->setSwallowTouches(true); touchListener->onTouchBegan = [this](Touch *touch, Event *event)->bool { m_lastMove = this->convertTouchToNodeSpace(touch); return true; }; touchListener->onTouchMoved = [this](Touch *touch, Event *event) { auto location = this->convertTouchToNodeSpace(touch); Vec2 v = Vec2(location.x - m_lastMove.x, location.y - m_lastMove.y); Vec2 des = m_gameLy->getPosition(); des.add(v); m_gameLy->setPosition(boundeEdge(des)); m_lastMove = location; }; touchListener->onTouchEnded = [this](Touch *touch, Event *event){}; touchListener->onTouchCancelled = [this](Touch *touch, Event *event){}; dispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); schedule(schedule_selector(HelloWorld::step)); return true; }
//第三关 void GameLayer::addGangti3(){ //墙壁 for (int i =1; i<=4; i++) { auto str2 =__String::createWithFormat("wall_%d",i); auto wall = node->getChildByName<Sprite*>(str2->getCString()); if (wall->getTag() == 25) { auto body2 = PhysicsBody::createBox(Size(wall->getContentSize().width,wall->getContentSize().height)); body2->setDynamic(false); body2->getShape(0)->setFriction(0); body2->getShape(0)->setRestitution(1); wall->setPhysicsBody(body2); wall->getPhysicsBody()->setContactTestBitmask(WALL_MASK); } } //石头墙 for (int i = 1; i<=4 ;i++ ) { auto str3 = __String::createWithFormat("wod_%d",i); Sprite* woods1 = node->getChildByName<Sprite*>(str3->getCString()); // log("tag = %d",woods1->getTag()); if (woods1->getTag() ==55) { auto body = PhysicsBody::createBox(woods1->getContentSize()); body->setDynamic(false); body->getShape(0)->setRestitution(1.3);//反弹力 body->getShape(0)->setFriction(0);//摩擦力 woods1->setPhysicsBody(body); woods1->getPhysicsBody()->setContactTestBitmask(WALL_MASK); } } //木头 for (int i = 1; i<=8 ;i++ ) { auto str = __String::createWithFormat("wood_%d",i); Sprite* woods1 = node->getChildByName<Sprite*>(str->getCString()); // log("tag = %d",woods1->getTag()); if (woods1->getTag() ==5) { auto body = PhysicsBody::createBox(woods1->getContentSize()); body->setDynamic(false); body->getShape(0)->setRestitution(1);//反弹力 body->getShape(0)->setFriction(0);//摩擦力 woods1->setPhysicsBody(body); woods1->getPhysicsBody()->setContactTestBitmask(WALL_MASK); } } //石头 for (int i =1; i<= 2; i++) { auto str3 =__String::createWithFormat("stone_%d",i); auto stone = node->getChildByName<Sprite*>(str3->getCString()); if (stone->getTag() == 45) { auto body3 = PhysicsBody::createCircle(stone->getContentSize().width/2); body3->setDynamic(false); body3->getShape(0)->setFriction(0); body3->getShape(0)->setRestitution(1.5);//弹力 stone->setPhysicsBody(body3); stone->getPhysicsBody()->setContactTestBitmask(WALL_MASK); } } }
//============================================================= //============================================================= bool CCScrollLayer::onTouchBegan(Touch *pTouch, Event *pEvent) { if (!isVisible()) // 父视图改变visible 不影响孩子的变量 //不可见依然接收touch { return false; } Node* fatherNode = getParent(); if(!fatherNode) return false; Point touchPointInWorld = pTouch->getLocation(); Rect selfRect = boundingBox(); Point selfOriginInWorld = fatherNode->convertToWorldSpace(selfRect.origin); Rect selfRectInWorld = Rect(selfOriginInWorld.x,selfOriginInWorld.y,selfRect.size.width,selfRect.size.height); if(selfRectInWorld.containsPoint(touchPointInWorld) == false) { return false; } for (Node *c = this->_parent; c != NULL; c = c->getParent()) { if (c->isVisible() == false) //若父亲有不可见的则不处理touch { return false; } Rect rect = c->boundingBox(); Node* parentNode = c->getParent(); if(parentNode) { Point originInWorld = parentNode->convertToWorldSpace(rect.origin); Rect rectInWorld = Rect(originInWorld.x,originInWorld.y,rect.size.width,rect.size.height); if(rectInWorld.containsPoint(touchPointInWorld) == false) { return false; } } } // CCSetIterator it = pTouches->begin(); Touch* touch = pTouch; m_beginPoint = touch->getLocation(); Node* parent = getParent(); Point localPoint = parent->convertToNodeSpace(m_beginPoint); Rect boundRect = boundingBox(); bool unmoveAbleFlag = getContentSize().equals(m_contentLayer->getContentSize());// CCSize::CCSizeEqualToSize(getContentSize(),m_contentLayer->getContentSize()); if(boundRect.containsPoint(localPoint) && unmoveAbleFlag==false) //点击开始在区域内 { m_containBeginTouchPointFlag = true; m_2fLastMoveDis = vertex2(0, 0); sendSelector(SSTE_TOUCH_BEGIN); if(m_decelerateFlag) { m_decelerateFlag = false; unschedule(schedule_selector(CCScrollLayer::decelerateTick)); } moveToEndPosition(false,m_contentLayer->getPosition()); return true; } else { m_containBeginTouchPointFlag = false; return false; } }
void EquipmentInfo::singleEquipmentInfo(int pkID, int typeClick) { equipmentPKID = pkID; for (unsigned int i = 0; i < tempEquipVector.size(); i ++) { if (tempEquipVector[ i ].ePKID == pkID) { auto singlePanel = dynamic_cast<Layout* >(Helper::seekWidgetByName(singleInfo, "Panel_Left")); // 获取属性面板 auto nameImageString = __String::createWithFormat("%d.png", localEquipVector[ tempEquipVector[ i ].eID - 94001 ].eID); auto nameImage = dynamic_cast<ImageView* >(Helper::seekWidgetByName(singlePanel, "Image_Equip_0")); // 设置物品图片 nameImage->loadTexture(nameImageString->getCString(), TextureResType::UI_TEX_TYPE_PLIST); nameImage->setScale(81.0f / 120.0f); auto nameText = dynamic_cast<Text* >(Helper::seekWidgetByName(singlePanel, "Label_Name")); // 装备名称 if (tempEquipVector[ i ].eLevel == 0) { auto equipLevel = __String::createWithFormat("%s", localEquipVector[ tempEquipVector[ i ].eID - 94001 ].eChinaName); nameText->setText(equipLevel->getCString()); } else { auto equipLevel = __String::createWithFormat("%s+%d", localEquipVector[ tempEquipVector[ i ].eID - 94001 ].eChinaName, tempEquipVector[ i ].eLevel); nameText->setText(equipLevel->getCString()); } for (int z = 60; z < 62; z ++) { singlePanel->removeChildByTag( z ); } // 功能按钮 auto equipButton = dynamic_cast<Button*>(Helper::seekWidgetByName(singlePanel, "Button_Equip")); // 装备按钮 equipButton->addTouchEventListener(this, toucheventselector(EquipmentInfo::equipClick)); equipButton->setVisible(false); equipButton->setTouchEnabled(false); auto changeButton = dynamic_cast<Button*>(Helper::seekWidgetByName(singlePanel, "Button_Change")); // 更换 changeButton->addTouchEventListener(this, toucheventselector(EquipmentInfo::changeClick)); changeButton->setVisible(false); changeButton->setTouchEnabled(false); auto unloadButton = dynamic_cast<Button*>(Helper::seekWidgetByName(singlePanel, "Button_Unload")); // 卸下 unloadButton->addTouchEventListener(this, toucheventselector(EquipmentInfo::unloadClick)); unloadButton->setVisible(false); unloadButton->setTouchEnabled(false); if (interGeneralEquipVector[ 0 ].equipID[ DataManager::getInstance()->equipType - 1 ] == 0) // 点击的位置没有装备 { equipButton->setVisible(true); equipButton->setTouchEnabled(true); if (false == NewComer::isGuideDone(1000)) /* 引导ID为0,且未完成 */ { _comer = NewComer::create(this, 1000, 4); } } else { if ( interGeneralEquipVector[ 0 ].equipPKID[ DataManager::getInstance()->equipType - 1 ] == pkID ) { unloadButton->setVisible(true); unloadButton->setTouchEnabled(true); } else { changeButton->setVisible(true); changeButton->setTouchEnabled(true); } } // 物品属性 auto proptyLabel1 = (Text*)singlePanel->getChildByName("Label_Propty_1"); proptyLabel1->setFontSize(FontSize); proptyLabel1->setVisible(false); auto proptyLabel2 = (Text*)singlePanel->getChildByName("Label_Propty_2"); proptyLabel2->setFontSize(FontSize); proptyLabel2->setVisible(false); auto label1 = Label::create(); label1->setSystemFontSize(FontSize); label1->setColor(Color3B(255, 76, 0)); label1->setTag(Label1); singlePanel->addChild(label1, 10); auto label2 = Label::create(); label2->setSystemFontSize(FontSize); label2->setColor(Color3B(255, 76, 0)); label2->setTag(Label2); singlePanel->addChild(label2, 10); auto goodsTypeString = __String::createWithFormat("%s", localEquipVector[ tempEquipVector[ i ].eID - 94001 ].ePositionName); auto goodsDesString = __String::createWithFormat("%s", localEquipVector[ tempEquipVector[ i ].eID - 94001 ].eDes); auto typeLabel = dynamic_cast<Text*>(Helper::seekWidgetByName(singlePanel, "Label_Num")); auto desLabel = (Text*)singlePanel->getChildByName("Label_Des"); typeLabel->setVisible(true); typeLabel->setText(goodsTypeString->getCString()); desLabel->setVisible(true); desLabel->ignoreContentAdaptWithSize(false); desLabel->setSize(Size(180, 150)); desLabel->setTextHorizontalAlignment(TextHAlignment::LEFT); desLabel->setText(goodsDesString->getCString()); switch (localEquipVector[ tempEquipVector[ i ].eID - 94001 ].ePositionType) { case PosTypeHead: { proptyLabel1->setVisible(true); proptyLabel2->setVisible(false); proptyLabel1->setText(mpFontChina->getComString("PD")->getCString()); auto hpString = __String::createWithFormat("%d", localEquipVector[ tempEquipVector[ i ].eID - 94001 ].ePD); label1->setPosition(Point(proptyLabel1->getPositionX() + proptyLabel1->getContentSize().width + 10, proptyLabel1->getPositionY())); label1->setString(hpString->getCString()); } break; case PosTypeArmour: { proptyLabel1->setVisible(true); proptyLabel2->setVisible(false); proptyLabel1->setText(mpFontChina->getComString("HP")->getCString()); auto hpString = __String::createWithFormat("%d", localEquipVector[ tempEquipVector[ i ].eID - 94001 ].eHP); label1->setPosition(Point(proptyLabel1->getPositionX() + proptyLabel1->getContentSize().width + 10, proptyLabel1->getPositionY())); label1->setString(hpString->getCString()); } break; case PosTypeDecorations: { proptyLabel1->setVisible(true); proptyLabel1->setText(mpFontChina->getComString("MD")->getCString()); proptyLabel2->setVisible(false); auto attackString = __String::createWithFormat("%d", localEquipVector[ tempEquipVector[ i ].eID - 94001 ].eMD); label1->setPosition(Point(proptyLabel1->getPositionX() + proptyLabel1->getContentSize().width + 10, proptyLabel1->getPositionY())); label1->setString(attackString->getCString()); } break; case PosTypeWeapons: { proptyLabel1->setVisible(true); proptyLabel2->setVisible(false); proptyLabel1->setText(mpFontChina->getComString("Attack")->getCString()); label1->setPosition(proptyLabel1->getPosition().x + proptyLabel1->getContentSize().width + 10, proptyLabel1->getPosition().y); auto hpString = __String::createWithFormat("%d", localEquipVector[ tempEquipVector[ i ].eID - 94001 ].eAtk); label1->setString(hpString->getCString()); } break; case PosTypeQi: { proptyLabel1->setVisible(true); proptyLabel2->setVisible(true); proptyLabel1->setText(mpFontChina->getComString("APR")->getCString()); label1->setPosition(proptyLabel1->getPosition().x + proptyLabel1->getContentSize().width + 10, proptyLabel1->getPosition().y); auto hpString = __String::createWithFormat("%.2f", localEquipVector[ tempEquipVector[ i ].eID - 94001 ].eAddCrit); label1->setString(hpString->getCString()); proptyLabel2->setText(mpFontChina->getComString("RPR")->getCString()); label2->setPosition(proptyLabel2->getPosition().x + proptyLabel2->getContentSize().width + 10, proptyLabel2->getPosition().y); auto hpString2 = __String::createWithFormat("%.2f", localEquipVector[ tempEquipVector[ i ].eID - 94001 ].eReduceCrit); label2->setString(hpString2->getCString()); } break; case PosTypeYi: { proptyLabel1->setVisible(true); proptyLabel2->setVisible(true); proptyLabel1->setText(mpFontChina->getComString("ARH")->getCString()); label1->setPosition(proptyLabel1->getPosition().x + proptyLabel1->getContentSize().width + 10, proptyLabel1->getPosition().y); auto hpString = __String::createWithFormat("%d", localEquipVector[ tempEquipVector[ i ].eID - 94001 ].eAddRealHurt); label1->setString(hpString->getCString()); proptyLabel2->setText(mpFontChina->getComString("RRH")->getCString()); label2->setPosition(proptyLabel2->getPosition().x + proptyLabel2->getContentSize().width + 10, proptyLabel2->getPosition().y); auto hpString2 = __String::createWithFormat("%d", localEquipVector[ tempEquipVector[ i ].eID - 94001 ].eReduceHurt); label2->setString(hpString2->getCString()); } break; } } } }
// on "init" you need to initialize your instance bool MapLayer::init() { ////////////////////////////// // 1. super init first if ( !LayerColor::initWithColor( Color4B( 255, 0, 0, 255 ))) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Point origin = Director::getInstance()->getVisibleOrigin(); auto img = Sprite::create("image/map.png"); // img->setPosition( getPosition()); // img->setContentSize( Size( MAP_WIDTH, MAP_HEIGHT )); img->setPosition( MAP_WIDTH/2, MAP_HEIGHT/2); this->addChild( img, 0 ); setContentSize( Size( MAP_WIDTH, MAP_HEIGHT ) ); setPosition( ( visibleSize.width - MAP_WIDTH ) / 2, ( visibleSize.height - MAP_HEIGHT ) / 2 ); // this->setContentSize( Size( 100, 100 )); //////////////////////////////// this->setTouchEnabled( true ); auto m_touchListener = EventListenerTouchOneByOne::create(); // m_touchListener->setSwallowTouches(true); m_touchListener->onTouchBegan = CC_CALLBACK_2(MapLayer::onTouchBegan, this); m_touchListener->onTouchMoved = CC_CALLBACK_2(MapLayer::onTouchMoved, this); m_touchListener->onTouchEnded = CC_CALLBACK_2(MapLayer::onTouchEnded, this); EventDispatcher* dispatcher = Director::getInstance()->getEventDispatcher(); dispatcher->addEventListenerWithFixedPriority( m_touchListener, 1 ); //////////////////////////////// auto keyboardListener = EventListenerKeyboard::create(); // EventDispatcher* dispatcher = Director::getInstance()->getEventDispatcher(); keyboardListener->onKeyPressed = CC_CALLBACK_2( MapLayer::onKeyPressed, this ); keyboardListener->onKeyReleased = CC_CALLBACK_2( MapLayer::onKeyReleased, this ); dispatcher->addEventListenerWithFixedPriority( keyboardListener, 1 ); // setKeyboardEnabled( true ); setKeyboardEnabled( true ); ///////////////////////////////////////////////////////////////////////////////////////////////////////// auto label = LabelTTF::create("test test.", "Arial", 30); // position the label on the center of the screen label->setPosition(Point(origin.x + visibleSize.width/2, origin.y + visibleSize.height - label->getContentSize().height)); label->setColor( Color3B( 255, 0, 0 )); // add the label as a child to this layer this->addChild(label, 1); return true; }
bool TrainingTower::init() { if (!Sprite::init()) //如果忘记了这句话则会在runApplication报错 { return false; } instance = GameManager::getInstance(); soldierToProduceCount = 0; isTrainingSpriteSelected = false; instance->totalSoldierNum = 0; setTowerType(7); setIsSelected(false); setGrade(0);//开始没有等级 setPower(40);//塔消耗电力 setMove(false);//开始不处于移动状态 setIsPowerEnough(true);//开始状态电力足够 setIsPowerConsumption(false);//该塔不耗电 towerSprite = Sprite::create("towerItem/Item8.png"); towerSprite->setScale(0.4); addChild(towerSprite, 5); trainingSprite = Sprite::create("traingButton.png"); //训练button,开始不显示,点击该建筑才显示 trainingSprite->setScale(0.25); auto sb = ScaleBy::create(1, 1.2); auto seq = Sequence::create(sb, sb->reverse(), NULL); auto rp = RepeatForever::create(seq); trainingSprite->runAction(rp); trainingSprite->setPosition(towerSprite->getBoundingBox().size.width-10,0); addChild(trainingSprite, 5); trainingSprite->setVisible(false); produceTime = 0;//初始化生产时间为0 produceTimeBarBg = Sprite::create("manaBarBg.png"); produceTimeBarBg->setScale(0.3); //0.45 produceTimeBarBg->setPosition(towerSprite->getPosition() + Point(0, 65)); addChild(produceTimeBarBg, 11); //待生产士兵的数目 soldierNum = Label::createWithTTF("", "b.ttf", 10); soldierNum->setPosition(produceTimeBarBg->getPosition()); addChild(soldierNum, 12); //生产时间条初始化 timeBar = ProgressTimer::create(Sprite::create("time.png")); timeBar->setScaleX(0.3); timeBar->setScaleY(2.2); timeBar->setType(ProgressTimer::Type::BAR); timeBar->setMidpoint(Point(0, 0.5)); timeBar->setBarChangeRate(Point(1, 0)); timeBar->setPercentage(produceTime); timeBar->setAnchorPoint(Point(0, 0.5)); timeBar->setPosition(produceTimeBarBg->getPosition() - Point(produceTimeBarBg->getBoundingBox().size.width / 2 - 5, 0)); addChild(timeBar, 10); //生产时间属性条不可见 timeBar->setVisible(false); produceTimeBarBg->setVisible(false); soldierNum->setVisible(false); //血量条背景图片 towerHpSprite = Sprite::create("manaBarBg.png"); towerHpSprite->setPosition(towerSprite->getPosition() + Point(0, 50)); towerHpSprite->setScale(0.3); addChild(towerHpSprite, 10); //炮塔血量 hp = 4; //炮塔血量进度条 towerHp = ProgressTimer::create(Sprite::create("soldierProduceTimeBar.png")); //参数是一个图片sprite towerHp->setScaleX(2); towerHp->setScaleY(5.2); towerHp->setType(ProgressTimer::Type::BAR); towerHp->setMidpoint(Point(0, 0.5f)); towerHp->setBarChangeRate(Point(1, 0)); towerHp->setPercentage(100); towerHp->setPosition(Point(towerHpSprite->getContentSize().width / 2, towerHpSprite->getContentSize().height / 3 * 2 - 10)); towerHpSprite->addChild(towerHp, 5); //初始化不可见 towerHp->setVisible(false); towerHpSprite->setVisible(false); addTouch();//添加触摸事件 listener->onTouchBegan = [=](Touch* pTouch, Event* pEvent){ auto target = static_cast<Sprite*>(pEvent->getCurrentTarget()); Point locationInNode = target->convertTouchToNodeSpace(pTouch); Size size = target->getContentSize(); Rect rect = Rect(0, 0, size.width, size.height); //log("rect size %f %f", size.width, size.height); if (rect.containsPoint(locationInNode)) { timeBar->setVisible(true); produceTimeBarBg->setVisible(true); trainingSprite->setVisible(true); soldierNum->setVisible(true); towerHp->setVisible(true); towerHpSprite->setVisible(true); return true; } else if (!isTrainingSpriteSelected)//这样就可以实现点击其他地方隐藏属性条的功能了 { timeBar->setVisible(false); produceTimeBarBg->setVisible(false); trainingSprite->setVisible(false); soldierNum->setVisible(false); towerHp->setVisible(false); towerHpSprite->setVisible(false); } return false; }; trainingButtonListener = EventListenerTouchOneByOne::create(); trainingButtonListener->onTouchBegan = [=](Touch* pTouch, Event* pEvent){ //这个是特殊声明 用来检测训练士兵按钮的点击,这种用法就是在要点击的图片上加listener auto target = static_cast<Sprite*>(pEvent->getCurrentTarget()); Point locationInNode = target->convertTouchToNodeSpace(pTouch); Size size = target->getContentSize(); Rect rect = Rect(0, 0, size.width, size.height); //log("rect size %f %f", size.width, size.height); if (rect.containsPoint(locationInNode) && trainingSprite->isVisible() && instance->totalSoldierNum<MAX_SOLDIER_NUM ) { if (instance->getMoney() >= 100) { isTrainingSpriteSelected = true; soldierToProduceCount++; instance->totalSoldierNum++;//士兵总数最多10个 char c[10]; sprintf(c, "%d", soldierToProduceCount); std::string str = c; soldierNum->setString(str); //金钱减少 instance->setMoney(instance->getMoney() - 100); char c1[10]; sprintf(c1, "%d", instance->getMoney()); std::string str1 = c1; instance->moneyLabel->setString(str1); } else //金钱不足 { auto sb = ScaleBy::create(0.3, 1.2); auto seq = Sequence::create(sb, sb->reverse(), NULL); instance->moneyLabel->runAction(seq); } return true; } else { isTrainingSpriteSelected = false; trainingSprite->setVisible(false); } return false; }; _eventDispatcher->addEventListenerWithSceneGraphPriority(trainingButtonListener, this->trainingSprite); this->schedule(schedule_selector(TrainingTower::produceSoldier), 0.1); return true; }
void PushBallScene::initBall() { m_pGlass = ToolSprite::create("images/select/glass_bottle0.png"); kAdapterScreen->setExactPosition(m_pGlass, 120, 0,Vec2::ZERO,kBorderLeft,kBorderNone); m_pGlass->setDelegate(this); m_pGlass->setAnchorPoint(Vec2::ZERO); m_pGlass->setIsMove(false); m_pGlass->setTag(GLASSTAG); m_pGlass->cancelEvent(true); Vec2 pos = m_pBG->convertToWorldSpace(Vec2(0,340+120)); m_pGlass->setPositionY(pos.y); this->addToContentLayer(m_pGlass,5); auto borderUpper = PhysicsBody::createEdgeChain(glass,29,PHYSICSBODY_MATERIAL_DEFAULT,10); m_pGlass->setPhysicsBody(borderUpper); Sprite* glassCover = Sprite::create("images/select/glass_bottle1.png"); glassCover->setAnchorPoint(Vec2::ZERO); glassCover->setTag(GLASSCOVERTAG); m_pGlass->addChild(glassCover,100); Vec2 _pos = m_pMac->convertToWorldSpace(Vec2(-48,323 + 250)); m_pGlass->setPosition(_pos); for(int i = 0;i<8;i++){ __String* sball = nullptr; sball = __String::createWithFormat("images/select/one_%s.png",ballStr[0].c_str()); if(i>3 && i<6){ if (ballStr[1]!="") { sball = __String::createWithFormat("images/select/one_%s.png",ballStr[1].c_str()); } }else if(i>6){ if (ballStr[2]!="") { sball = __String::createWithFormat("images/select/one_%s.png",ballStr[2].c_str()); } } auto ball = Sprite::create(sball->getCString()); // ball->setPosition(m_pGlass->convertToWorldSpace(Vec2(130,260))); ball->setPosition(m_pGlass->convertToWorldSpace(Vec2(130,170))); this->addToContentLayer(ball); // ball->setPosition(Vec2(130,260)); // m_pGlass->addChild(ball); auto body = PhysicsBody::createCircle(ball->getContentSize().width / 2 - 5); ball->setPhysicsBody(body); body->getShape(0)->setMass(5010); body->getShape(0)->setRestitution(0); } // RotateBy* move =RotateBy::create(5.0, 360); // m_pGlass->runAction(Sequence::create(move, NULL)); // }
bool PopWindow::init() { if ( LayerColor::initWithColor(Color4B(0,0,0,0)) ) { _goto = GOTO::NONE; auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = [](Touch* touch, Event* event){ return true; }; _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); _bk = Sprite::create("pop_bk.png"); _bk->setScale(0.1f); _bk->setPosition(g_visibleRect.center); _bk->setAnchorPoint(Point::ANCHOR_MIDDLE); _bk->runAction(EaseBackOut::create(ScaleTo::create(0.1f, 1.0f))); this->addChild(_bk); TTFConfig turnTTFConfig; turnTTFConfig.outlineSize = 3; turnTTFConfig.fontSize = 30; turnTTFConfig.fontFilePath = "fonts/britanic bold.ttf"; _contentLabel = Label::createWithTTF(turnTTFConfig, "Connecting...", TextHAlignment::CENTER, 400); _contentLabel->setAnchorPoint(Point::ANCHOR_MIDDLE_RIGHT); _contentLabel->setPosition(_bk->getContentSize().width/2+20,_bk->getContentSize().height/2); _contentLabel->setSpacing(-5); _contentLabel->enableOutline(Color4B::BLACK); _bk->addChild(_contentLabel); _loadingSprite = Sprite::create("android.png"); _loadingSprite->setScale(0.7f); _loadingSprite->setAnchorPoint(Point::ANCHOR_MIDDLE_LEFT); _loadingSprite->setPosition(_contentLabel->getPosition()+Point(20,0)); _loadingSprite->runAction(RepeatForever::create(Sequence::create(MoveBy::create(0.5f, Point(0,20)),MoveBy::create(0.5f, Point(0,-20)), nullptr))); _bk->addChild(_loadingSprite); auto btn_menuitem = MenuItemImage::create("pop_btn.png","pop_btn.png",CC_CALLBACK_1(PopWindow::menuCallback, this)); btn_menuitem->setAnchorPoint(Point::ANCHOR_MIDDLE_BOTTOM); btn_menuitem->setPosition(_bk->getContentSize().width/2,100); _btn_menu = Menu::create(btn_menuitem,nullptr); _btn_menu->setPosition(Point::ZERO); _btn_menu->setVisible(false); _bk->addChild(_btn_menu); TTFConfig t_turnTTFConfig; t_turnTTFConfig.outlineSize = 3; t_turnTTFConfig.fontSize = 20; t_turnTTFConfig.fontFilePath = "fonts/britanic bold.ttf"; _btn_label = Label::createWithTTF(t_turnTTFConfig, "OK", TextHAlignment::CENTER, 400); _btn_label->setAnchorPoint(Point::ANCHOR_MIDDLE); _btn_label->setPosition(btn_menuitem->getContentSize().width/2, btn_menuitem->getContentSize().height/2); _btn_label->setSpacing(-5); _btn_label->enableOutline(Color4B::BLACK); btn_menuitem->addChild(_btn_label); } return true; }
// on "init" you need to initialize your instance bool TestScene::init() { ////////////////////////////// // 1. super init first if (!Scene::init()) { return false; } cocos2d::Size visibleSize = cocos2d::Director::getInstance()->getVisibleSize(); cocos2d::Vec2 origin = cocos2d::Director::getInstance()->getVisibleOrigin(); auto closeItem = cocos2d::MenuItemImage::create("CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(TestScene::menuCloseCallback, this)); closeItem->setPosition(cocos2d::Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width / 2, origin.y + closeItem->getContentSize().height / 2)); auto menu = cocos2d::Menu::create(closeItem, NULL); menu->setPosition(cocos2d::Vec2::ZERO); addChild(menu, 1); //Navigation UI NavUI* navui = new NavUI(ui_event_manager); ui_event_manager->subscribe<NavUI::Next>(*this); ui_event_manager->subscribe<NavUI::Prev>(*this); navui->setEnabled(true); navui->setVisible(true); addInterface(NavUI::id,navui); navui->setPosition(cocos2d::Vec2(visibleSize.width * 0.5f, visibleSize.height * 0.17f)); //Saving UI SavingUI* saveui = new SavingUI(); saveui->setEnabled(false); saveui->setVisible(false); addInterface(SavingUI::id,saveui); saveui->setPosition(cocos2d::Vec2(visibleSize.width * 0.5f, visibleSize.height * 0.67f)); //TimerUI TimerUI* timerui = new TimerUI(); timerui->setEnabled(false); timerui->setVisible(false); addInterface(TimerUI::id,timerui); timerui->setPosition(cocos2d::Vec2(visibleSize.width * 0.5f, visibleSize.height * 0.67f)); //*/ ///PlayersListUI PlayersListUI* playerslistui = new PlayersListUI(); playerslistui->setEnabled(false); playerslistui->setVisible(false); addInterface(PlayersListUI::id,playerslistui); playerslistui->setPosition(cocos2d::Vec2(visibleSize.width * 0.5, visibleSize.height * 0.5)); //*/ /*/Error UI ErrorUI* errorui = new ErrorUI(); auto errorroot = errorui->getRoot(); addChild(errorroot); errorroot->setEnabled(false); errorroot->setVisible(false); m_ui[ErrorUI::id] = errorui; errorroot->setPosition(cocos2d::Vec2(visibleSize.width * 0.75, visibleSize.height * 0.25)); errorui->setRefreshCallback([this, errorui](){ errorui->deactivate(); }); errorui->setSkipCallback([this, errorui](){ errorui->deactivate(); }); //*/ // auto sprite = cocos2d::Sprite::create("HelloWorld.png"); sprite->setScaleX((visibleSize.width / 2 - closeItem->getContentSize().width) / sprite->getContentSize().width); sprite->setScaleY((visibleSize.height / 2 - closeItem->getContentSize().height) / sprite->getContentSize().height); sprite->setPosition(cocos2d::Vec2((visibleSize.width / 2 + closeItem->getPositionX() - closeItem->getContentSize().width / 2) / 2, (visibleSize.height / 2 + closeItem->getPositionY() + closeItem->getContentSize().height / 2) / 2)); addChild(sprite, 0); sprite->setVisible(false); //*/ //ShopUI ShopUI* shopui = new ShopUI(); shopui->setEnabled(false); shopui->setVisible(false); addInterface(ShopUI::id,shopui); shopui->setPosition(cocos2d::Vec2(visibleSize.width * 0.5f, visibleSize.height * 0.67f)); //DownloadUI DownloadUI* dlui = new DownloadUI(); dlui->setEnabled(false); dlui->setVisible(false); addInterface(DownloadUI::id,dlui); dlui->setPosition(cocos2d::Vec2(visibleSize.width * 0.5f, visibleSize.height * 0.67f)); //WebUI WebUI* webui = new WebUI(); webui->setEnabled(false); webui->setVisible(false); addInterface(WebUI::id,webui); webui->setPosition(cocos2d::Vec2(visibleSize.width * 0.5f, visibleSize.height * 0.67f)); //LogUI LogUI* logui = new LogUI(); logui->setEnabled(false); logui->setVisible(false); addInterface(LogUI::id, logui); logui->setPosition(cocos2d::Vec2(visibleSize.width * 0.5f, visibleSize.height * 0.67f)); //activating first UI : saveui->setEnabled(true); saveui->setVisible(true); currentUI = SavingUI::id; navui->setTitle(currentUI); m_time = cocos2d::ui::Text::create("", "Arial", 20); m_time->setPosition(cocos2d::Vec2(sprite->getPositionX(), closeItem->getPositionY())); addChild(m_time); g_gameLogic->getLocalDataManager().getEventManager()->subscribe<WkCocos::LocalData::Events::Error>(*this); g_gameLogic->getPlayer().player_events->subscribe<WkCocos::Player::Error>(*this); //g_gameLogic->getPlayer().getOnlineDatamgr()->getEventManager()->subscribe<WkCocos::OnlineData::Events::ServerTime>(*this); return true; }
bool Help::init() { if (!Layer::init()) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); //背景精灵 if (getPass() == 1) { auto bg1 = Sprite::create("help_bg1.jpg"); //为适应屏幕进行缩放 bg1->setScaleX((float)visibleSize.width / (float)bg1->getContentSize().width); bg1->setScaleY((float)visibleSize.height / (float)bg1->getContentSize().height); bg1->setPosition(Vec2(origin.x + visibleSize.width / 2, 0)); bg1->setAnchorPoint(Vec2(0.5, 0)); bg1->setTag(101); this->addChild(bg1, 0); } else if (getPass() == 2) { auto bg1 = Sprite::create("help_bg2.jpg"); //为适应屏幕进行缩放 bg1->setScaleX((float)visibleSize.width / (float)bg1->getContentSize().width); bg1->setScaleY((float)visibleSize.height / (float)bg1->getContentSize().height); bg1->setPosition(Vec2(origin.x + visibleSize.width / 2, 0)); bg1->setAnchorPoint(Vec2(0.5, 0)); bg1->setTag(101); this->addChild(bg1, 0); } else if (getPass() == 3) { auto bg1 = Sprite::create("help_bg3.jpg"); //为适应屏幕进行缩放 bg1->setScaleX((float)visibleSize.width / (float)bg1->getContentSize().width); bg1->setScaleY((float)visibleSize.height / (float)bg1->getContentSize().height); bg1->setPosition(Vec2(origin.x + visibleSize.width / 2, 0)); bg1->setAnchorPoint(Vec2(0.5, 0)); bg1->setTag(101); this->addChild(bg1, 0); } else if (getPass() == 4) { auto bg1 = Sprite::create("help_bg4.png"); //为适应屏幕进行缩放 bg1->setScaleX((float)visibleSize.width / (float)bg1->getContentSize().width); bg1->setScaleY((float)visibleSize.height / (float)bg1->getContentSize().height); bg1->setPosition(Vec2(origin.x + visibleSize.width / 2, 0)); bg1->setAnchorPoint(Vec2(0.5, 0)); bg1->setTag(101); this->addChild(bg1, 0); } else if (getPass() == 5) { auto bg1 = Sprite::create("bg_5.png"); //为适应屏幕进行缩放 bg1->setScaleX((float)visibleSize.width / (float)bg1->getContentSize().width); bg1->setScaleY((float)visibleSize.height / (float)bg1->getContentSize().height); bg1->setPosition(Vec2(origin.x + visibleSize.width / 2, 0)); bg1->setAnchorPoint(Vec2(0.5, 0)); bg1->setTag(101); this->addChild(bg1, 0); } auto MagicItem = MenuItemImage::create("continue.png", "continue2.png", CC_CALLBACK_1(Help::menuContinueCallback, this)); MagicItem->setPosition(Vec2(visibleSize.width - MagicItem->getContentSize().width - 20, MagicItem->getContentSize().height * 2)); MagicItem->setAnchorPoint(Vec2(0.5, 0.5)); auto menu = Menu::create(MagicItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); return true; }
// on "init" you need to initialize your instance // 初始化当前这个层 bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } std::string name = "jack";//直接赋值 log("name = %s",name);//直接这样会出现乱码问题,因为log用的不对 //我们可以去看log函数:void CC_DLL log(const char * format, ...) CC_FORMAT_PRINTF(1, 2);类型是const char* log("name = %s", name.c_str()); std::string *name1 = new std::string("jack");//直接赋值 log("name1 = %s", name1->c_str()); auto visibleSize = Director::getInstance()->getVisibleSize();//得到屏幕的大小(可见区域大小) Vec2 origin = Director::getInstance()->getVisibleOrigin();//得到可见区域大小的左下角坐标 ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object // 得到图片菜单 以及设置回调函数 auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); //关闭的按钮 closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 , origin.y + closeItem->getContentSize().height/2)); //把菜单项放到菜单里 auto menu = Menu::create(closeItem, NULL); //指定菜单的位置 设置显示的坐标位置 menu->setPosition(Vec2::ZERO); this->addChild(menu, 1);//把菜单放到当前层 __String *name2 = __String::create("Hi,Tony");//得到对象指针,因为是通过静态create函数获取的,不需要我们delete log("name = %s", name2->getCString()); const char* cstring = "Hi,Tonny"; __String *name3 = __String::createWithFormat("%s", cstring);//将char转换为__String std::string string = "Hi,Tonny"; __String *name4 = __String::createWithFormat("%s", string.c_str());//将std::string转换为__String int num = 123; __String *ns = __String::createWithFormat("%d", num);//这种方式可以转换很多其他类型 log("%d",ns->intValue()); //解决中文乱码 __String *ns2 = __String::create("大家好"); const char* cns; #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) std::string sns = MyUtility::gbk_2_utf8(ns2->getCString()); cns = sns.c_str(); #else cns = ns2->getCString(); #endif log("%s", cns); auto label = LabelTTF::create(cns, "Arial", 24);//在cocos2d 3.01时,认为已经过时了,但是这种用法还是能用 // 3. add your codes below... //标签 也就是中间显示的那个文字 以及加载字体 //auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24); //指定标签的位置 label->setPosition(Vec2(origin.x + visibleSize.width/2, origin.y + visibleSize.height - label->getContentSize().height)); //把标签加入到层中 this->addChild(label, 1,123);//设置tag,方便后面获取 //指定一个图片的精灵 auto sprite = Sprite::create("HelloWorld.png"); // 设置图片精灵的位置 sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); //把图片精灵加入到层中 this->addChild(sprite, 0); auto label1 = LabelAtlas::create("HelloWorld", "fonts/tuffy_bold_italic-charmap.png", 48, 66, ' '); label1->setPosition(Vec2(visibleSize.width / 2 - label1->getContentSize().width / 2, visibleSize.height - label1->getContentSize().height)); this->addChild(label1, 1); auto label2 = LabelBMFont::create("HelloWord","fonts/BMFont.fnt"); label2->setPosition(Vec2(visibleSize.width / 2, visibleSize.height - label2->getContentSize().height)); this->addChild(label2,1); return true; }
bool Level::init() { if (!Layer::init()) { return false; } Size winSize = Director::getInstance()->getWinSize(); // init map bool bRet = false; do { CC_BREAK_IF(!Layer::init()); this->setmap(TMXTiledMap::create("map.tmx")); this->settiledMap(_map->layerNamed("tiledMap")); _tiledMap->setAnchorPoint(Vec2(0, 1)); _tiledMap->setPosition(Vec2(0,winSize.height)); this->addChild(_map, -1); bRet = true; } while (0); // add actors SpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("pd_sprites.plist"); _actors = SpriteBatchNode::create("pd_sprites.pvr.ccz"); //_actors->getTexture()->setAliasTexParameters(); this->addChild(_actors, 0); // init hero this->initHero(); // add buttons SpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("button.plist"); _buttons = SpriteBatchNode::create("button.pvr.ccz"); _buttons->getTexture()->setAliasTexParameters(); this->addChild(_buttons); // init buttons auto _attackSprite = Sprite::createWithSpriteFrameName("*****@*****.**"); auto _jumpSprite = Sprite::createWithSpriteFrameName("*****@*****.**"); _attackSprite->setPosition(winSize.width - _attackSprite->getContentSize().width/2, _attackSprite->getContentSize().height/2); _jumpSprite->setPosition(winSize.width - _jumpSprite->getContentSize().width*4/3, _jumpSprite->getContentSize().height*4/3); this->addChild(_attackSprite, 1); this->addChild(_jumpSprite, 1); // add listeners auto _attackListener = EventListenerTouchOneByOne::create(); _attackListener->onTouchBegan = [&](Touch *ptouch, Event *pevent) -> bool{ auto target = static_cast<Sprite*>(pevent->getCurrentTarget()); Point locationInNode = target->convertToNodeSpace(ptouch->getLocation()); Size s = target->getContentSize(); Rect rect = Rect(0, 0, s.width, s.height); if (rect.containsPoint(locationInNode)) { auto fram = SpriteFrameCache::getInstance()->getSpriteFrameByName("*****@*****.**"); target->setSpriteFrame(fram); _hero->attack(); return true; } return false; }; _attackListener->onTouchEnded = [&](Touch *ptouch, Event *pevent){ auto target = static_cast<Sprite*>(pevent->getCurrentTarget()); auto fram = SpriteFrameCache::getInstance()->getSpriteFrameByName("*****@*****.**"); target->setSpriteFrame(fram); //_hero->idle(); }; auto _jumpListener = EventListenerTouchOneByOne::create(); _jumpListener->onTouchBegan = [&](Touch *ptouch, Event *pevent) -> bool{ auto target = static_cast<Sprite*>(pevent->getCurrentTarget()); Point locationInNode = target->convertToNodeSpace(ptouch->getLocation()); Size s = target->getContentSize(); Rect rect = Rect(0, 0, s.width, s.height); if (rect.containsPoint(locationInNode)) { auto fram = SpriteFrameCache::getInstance()->getSpriteFrameByName("*****@*****.**"); target->setSpriteFrame(fram); _hero->jump(); return true; } return false; }; _jumpListener->onTouchEnded = [&](Touch *ptouch, Event *pevent){ auto target = static_cast<Sprite*>(pevent->getCurrentTarget()); auto fram = SpriteFrameCache::getInstance()->getSpriteFrameByName("*****@*****.**"); target->setSpriteFrame(fram); //_hero->idle(); }; _eventDispatcher->addEventListenerWithSceneGraphPriority(_attackListener, _attackSprite); _eventDispatcher->addEventListenerWithSceneGraphPriority(_jumpListener, _jumpSprite); // update this->scheduleUpdate(); return bRet; }
Layout* PageView::createPage() { Layout* newPage = Layout::create(); newPage->setContentSize(getContentSize()); return newPage; }
// on "init" you need to initialize your instance bool Scene102::init() { ////////////////////////////// // 1. super init first if (!Layer::init()) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); Size size; SpriteFrameCache::getInstance()->addSpriteFramesWithFile("Scene101/scene101.plist"); SpriteFrameCache::getInstance()->addSpriteFramesWithFile("Scene101/scene101bg.plist"); //以 Sprite 作為背景 Sprite *bkimage = Sprite::createWithSpriteFrameName("s101bgimg.png"); // 使用 create 函式,給予檔名即可 bkimage->setPosition(Vec2(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y)); // 位置通常放置在螢幕正中間 this->addChild(bkimage, 0); // 自行增加 sprite 將 bean01.png 到螢幕正中間 // create and initialize a label, add a label shows "Scene 101" auto label = Label::createWithTTF("Scene 101", "fonts/Marker Felt.ttf", 32); label->setAlignment(cocos2d::TextHAlignment::CENTER); // 預設靠左對齊 label->setWidth(100); // 設定每行文字的顯示寬度 size = label->getContentSize(); label->setPosition(Vec2(origin.x + visibleSize.width - size.width / 2 - 10, origin.y + visibleSize.height - size.height / 2 - 10)); this->addChild(label, 1); this->_sceneno = 102; strcpy(this->_cSceneNo, "Scene 102"); //一般(非中文字)文字的顯示方式 _label1 = Label::createWithBMFont("fonts/couriernew32.fnt", "Scene 101"); size = _label1->getContentSize(); _label1->setColor(Color3B::WHITE); _label1->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - size.height)); this->addChild(_label1, 1); // 中文字的顯示方式 auto strings = FileUtils::getInstance()->getValueMapFromFile("scene101/strings.xml"); std::string str1 = strings["chinese1"].asString(); std::string str2 = strings["chinese2"].asString(); auto label2 = Label::createWithBMFont("fonts/hansans48.fnt", str1); auto label3 = Label::createWithBMFont("fonts/hansans48.fnt", str2); size = label2->getContentSize(); label2->setColor(Color3B(255, 238, 217)); label2->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - 80 - size.height)); this->addChild(label2, 1); label3->setColor(Color3B(250, 251, 170)); size = label3->getContentSize(); label3->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - 140 - size.height)); this->addChild(label3, 1); // add Return Button this->returnbtn = Sprite::createWithSpriteFrameName("returnbtn.png"); size = returnbtn->getContentSize(); this->returnbtn->setPosition(Vec2(origin.x + size.width / 2 + 5, origin.y + visibleSize.height - size.height / 2 - 5)); Point pos = returnbtn->getPosition(); this->rectReturn = Rect(pos.x - size.width / 2, pos.y - size.height / 2, size.width, size.height); this->addChild(returnbtn, 1); // add Replay Button this->replaybtn = Sprite::createWithSpriteFrameName("replaybtn.png"); size = replaybtn->getContentSize(); this->replaybtn->setPosition(Vec2(origin.x + size.width / 2 + 90, origin.y + visibleSize.height - size.height / 2 - 5)); pos = replaybtn->getPosition(); this->rectReplay = Rect(pos.x - size.width / 2, pos.y - size.height / 2, size.width, size.height); this->addChild(replaybtn, 1); // add Cuber Button this->cuberbtn = Sprite::createWithSpriteFrameName("cuberbtn1.png"); size = cuberbtn->getContentSize(); this->cuberbtn->setPosition(Vec2(origin.x + visibleSize.width - size.width / 2, origin.y + visibleSize.height - size.height / 2 - 60)); pos = cuberbtn->getPosition(); this->rectCuber = Rect(pos.x - size.width / 2, pos.y - size.height / 2, size.width, size.height); this->addChild(cuberbtn, 1); _listener1 = EventListenerTouchOneByOne::create(); //創建一個一對一的事件聆聽器 _listener1->onTouchBegan = CC_CALLBACK_2(Scene102::onTouchBegan, this); //加入觸碰開始事件 _listener1->onTouchMoved = CC_CALLBACK_2(Scene102::onTouchMoved, this); //加入觸碰移動事件 _listener1->onTouchEnded = CC_CALLBACK_2(Scene102::onTouchEnded, this); //加入觸碰離開事件 this->_eventDispatcher->addEventListenerWithSceneGraphPriority(_listener1, this); //加入剛創建的事件聆聽器 this->schedule(CC_SCHEDULE_SELECTOR(Scene102::doStep)); return true; }
float PageView::getPositionXByIndex(ssize_t idx)const { return (getContentSize().width * (idx-_curPageIdx)); }
void BattleEntityPlayer::OnAnimationCreate(EntityAnimation* pNode) { pNode->setPosition(ccp(getAnchorPointInPoints().x, getAnchorPointInPoints().y - getContentSize().height*0.5)); }
void RichText::formarRenderers() { if (_ignoreSize) { float newContentSizeWidth = 0.0f; float newContentSizeHeight = 0.0f; CCArray* row = (CCArray*)(_elementRenders[0]); float nextPosX = 0.0f; for (unsigned int j=0; j<row->count(); j++) { CCNode* l = (CCNode*)(row->objectAtIndex(j)); l->setAnchorPoint(CCPointZero); l->setPosition(ccp(nextPosX, 0.0f)); _elementRenderersContainer->addChild(l, 1, j); CCSize iSize = l->getContentSize(); newContentSizeWidth += iSize.width; newContentSizeHeight = MAX(newContentSizeHeight, iSize.height); nextPosX += iSize.width; } _elementRenderersContainer->setContentSize(CCSizeMake(newContentSizeWidth, newContentSizeHeight)); } else { float newContentSizeHeight = 0.0f; float *maxHeights = new float[_elementRenders.size()]; for (unsigned int i=0; i<_elementRenders.size(); i++) { CCArray* row = (CCArray*)(_elementRenders[i]); float maxHeight = 0.0f; for (unsigned int j=0; j<row->count(); j++) { CCNode* l = (CCNode*)(row->objectAtIndex(j)); maxHeight = MAX(l->getContentSize().height, maxHeight); } maxHeights[i] = maxHeight; newContentSizeHeight += maxHeights[i]; } float nextPosY = _customSize.height; for (unsigned int i=0; i<_elementRenders.size(); i++) { CCArray* row = (CCArray*)(_elementRenders[i]); float nextPosX = 0.0f; nextPosY -= (maxHeights[i] + _verticalSpace); for (unsigned int j=0; j<row->count(); j++) { CCNode* l = (CCNode*)(row->objectAtIndex(j)); l->setAnchorPoint(CCPointZero); l->setPosition(ccp(nextPosX, nextPosY)); _elementRenderersContainer->addChild(l, 1, i*10 + j); nextPosX += l->getContentSize().width; } } _elementRenderersContainer->setContentSize(_size); delete [] maxHeights; } _elementRenders.clear(); if (_ignoreSize) { CCSize s = getContentSize(); _size = s; } else { _size = _customSize; } }