bool Valkyrie::init(const std::string& name){ if (!Armature::init(name)){ return false; } CCLOG("Valkyrie init"); battle_state = BattleState::NORMALSTATE; action_state = ActionState::STANDBY; //phy auto body = PhysicsBody::createBox(Size(getContentSize().width * SCALE,getContentSize().height * SCALE),common_material); body->setCategoryBitmask(VALKYRIE_CATA_MASK); body->setContactTestBitmask(VALKYRIE_CONTACT_MASK); body->setCollisionBitmask(0xFFFFFFFF); m_range = PhysicsShapeCircle::create(100); m_range->setCategoryBitmask(RANGE_CATA_MASK); m_range->setContactTestBitmask(RANGE_CONTACT_MASK); m_range->setCollisionBitmask(RANGE_COLLISION_MASK); m_range->setMass(0.1f); m_range->setTag(911); body->addShape(m_range); CCLOG("m_range 's tag is %d",m_range->getTag()); body->setRotationEnable(false); body->setDynamic(true); setPhysicsBody(body); setScale(SCALE); return true; }
void BreakoutMainScene::createBlock() { for (int i = 0; i < BLOCK_NUMBER; i++) { auto block = Sprite::create("breakout_img/blocks.png"); auto blockBody = PhysicsBody::createBox(Size(block->getContentSize().width , block->getContentSize().height) , PHYSICSBODY_MATERIAL_DEFAULT); blockBody->getShape(0)->setRestitution(0.0f); // dan hoi blockBody->getShape(0)->setFriction(0.0f); // ma sat blockBody->getShape(0)->setDensity(1.0f); // mat do blockBody->setContactTestBitmask(0x00000001); blockBody->setDynamic(false); blockBody->setGravityEnable(false); block->setPhysicsBody(blockBody); float offsetPosX = block->getContentSize().width/2 + 200*(i) + block->getContentSize().width; block->setPosition(Vec2(offsetPosX , 450)); block->setTag(Tag::T_Block); this->addChild(block); } }
void MiniBoss::createBullet(Vec2 position, bool leftToRight) { auto bullet = Sprite::create("images/bullet.png"); bullet->setPosition(position); auto bulletBody = PhysicsBodyParser::getInstance()->bodyFormJson(bullet, "bullet", PHYSICSBODY_MATERIAL_DEFAULT); bulletBody->setContactTestBitmask(true); bulletBody->setCollisionBitmask(ENEMY_BULLET_BISMASK); bulletBody->setDynamic(true); bullet->setPhysicsBody(bulletBody); //bullet action MoveBy *movement; if (leftToRight) movement = MoveBy::create(1, Vec2(horizontalFlightDistance, 0)); else movement = MoveBy::create(1, Vec2(-horizontalFlightDistance, 0)); auto remove = CallFunc::create(bullet, callfunc_selector(Sprite::removeFromParent)); bullet->runAction(Sequence::create(movement, remove, NULL)); layer->addChild(bullet); }
bool MonsterC::init() { count = 0; visibleSize = Director::getInstance()->getVisibleSize(); Sprite::initWithFile("monster/orangetriangle.png"); body = PhysicsBody::createCircle(this->getContentSize().width/2); body->setGravityEnable(1); //设置怪物的速度; // auto tmpx = sqrt(visibleSize.width / 5); // auto tmpx = visibleSize.width / 100000; Vect impulse = Vect(0.0, 0.0f); body->setVelocity(impulse); body->setRotationEnable(false);//设置怪物能不能滚动; setPhysicsBody(body); schedule(schedule_selector(MonsterC::MyUpdate), 0.2f); //每0.2秒执行一次 contactListener = EventListenerPhysicsContact::create(); contactListener->onContactBegin = CC_CALLBACK_1(MonsterC::onContactBegin, this); contactListener->onContactPostSolve = CC_CALLBACK_2(MonsterC::onContactPostSolve, this); contactListener->onContactPreSolve = CC_CALLBACK_2(MonsterC::onContactPreSolve, this); contactListener->onContactSeparate = CC_CALLBACK_1(MonsterC::onContactSeparate, this); Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(contactListener, this); return true; }
bool RoleEmemyBig::init() { ////////////////////////////// // 1. super init first if (!Sprite::initWithSpriteFrameName("hero1.png")) { return false; } setTag(TAG_ENEMY_PLANE); auto body = PhysicsBody::createBox(getContentSize()); body->setGroup(PHYSICAL_BODY_ENEMY_GROUP); body->setCategoryBitmask(PHYSICAL_BODY_ENEMY_BITMASK_CATEGORY); body->setContactTestBitmask(PHYSICAL_BODY_ENEMY_BITMASK_CONTACT_TEST); body->setCollisionBitmask(PHYSICAL_BODY_ENEMY_BITMASK_COLLISION); setPhysicsBody(body); setRotation(-90); Point endPos = Point(0, 100); runAction( Sequence::create(MoveTo::create(3.0, endPos), CallFunc::create( CC_CALLBACK_0(RoleEmemyBig::doRemoveSelf, this, this)), NULL)); return true; }
void LevelFifteen::callbackC(Node* sender) { auto visibleSize = Director::getInstance()->getVisibleSize(); auto pictureName = 1 + rand() % 27; auto str = String::createWithFormat("%d.png", pictureName)->getCString(); auto ballTwo2 = Sprite::createWithSpriteFrameName(str); ballTwo2->setPosition(Vec2(visibleSize.width / 2.0f, visibleSize.height - 90)); PhysicsBody* ballBodyTwo = nullptr; if (pictureName <= 9) { ballBodyTwo = PhysicsBody::createBox(ballTwo2->getContentSize(), PHYSICSBODY_MATERIAL_DEFAULT); } else if (pictureName > 9 && pictureName <= 18) { ballBodyTwo = PhysicsBody::createCircle(ballTwo2->getContentSize().width / 2.0f, PHYSICSBODY_MATERIAL_DEFAULT); } else if (pictureName > 18 && pictureName <= 21) { Vec2 vec[] = { Vec2(-22.50000, 22.00000), Vec2(24.00000, 10.00000), Vec2(-10.00000, -24.00000) }; ballBodyTwo = PhysicsBody::createPolygon(vec, 3); } else if (pictureName > 21 && pictureName <= 24) { Vec2 vec[] = { Vec2(-15.50000, 15.00000), Vec2(15.50000, 6.00000), Vec2(-7.00000, -15.50000) }; ballBodyTwo = PhysicsBody::createPolygon(vec, 3); } else if (pictureName > 24 && pictureName <= 27) { Vec2 vec[] = { Vec2(-8.00000, 8.00000), Vec2(7.50000, 3.00000), Vec2(-4.00000, -7.50000) }; ballBodyTwo = PhysicsBody::createPolygon(vec, 3); } //是否设置物体为静态 //ballBodyTwo->setDynamic(false); ballBodyTwo->getShape(0)->setRestitution(1.0f); ballBodyTwo->getShape(0)->setFriction(0.0f); ballBodyTwo->getShape(0)->setDensity(1.0f); ballBodyTwo->setGravityEnable(false); ballBodyTwo->setCategoryBitmask(2);// 分类掩码 ballBodyTwo->setCollisionBitmask(1 | 2 | 4 | 8);// 碰撞掩码 ballBodyTwo->setContactTestBitmask(1 | 8);// 接触测试掩码 ballBodyTwo->addMass(1000.0f); int flag = CCRANDOM_0_1() * 2; auto num = 0; switch (flag) { case 0: num = -1; break; case 1: num = 1; break; default: break; } auto force1 = Vec2(CCRANDOM_0_1()*10000.0f*num, -300000.0f); ballBodyTwo->applyImpulse(force1); ballTwo2->setPhysicsBody(ballBodyTwo); this->addChild(ballTwo2); }
bool PlayScene::init() { ////////////////////////////// // 1. super init first if (!LayerColor::initWithColor(Color4B(255, 255, 255, 255))) { return false; } visibleSize = Director::getInstance()->getVisibleSize(); score = 0; isDead = false; //Boundary auto edgeSp = Sprite::create(); auto boundBody = PhysicsBody::createEdgeBox(visibleSize, PHYSICSBODY_MATERIAL_DEFAULT, 3); edgeSp->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2)); edgeSp->setPhysicsBody(boundBody); this->addChild(edgeSp); //Contact Listener auto contactListener = EventListenerPhysicsContact::create(); contactListener->onContactBegin = CC_CALLBACK_1(PlayScene::onContactBegin, this); Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(contactListener, this); //character character = new Character(this, visibleSize); //Touch Listener auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = CC_CALLBACK_2(PlayScene::onTouchBegan, this); listener->onTouchMoved = CC_CALLBACK_2(PlayScene::onTouchMoved, this); listener->onTouchEnded = CC_CALLBACK_2(PlayScene::onTouchEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); /*score Label*/ scoreLabel = Label::createWithTTF("0", "fonts/Bauhaus_.ttf", 25); scoreLabel->setAnchorPoint(Vec2(1.0f, 0.5f)); scoreLabel->setPosition(Vec2(visibleSize.width - 10.0f, visibleSize.height - scoreLabel->getContentSize().height)); this->addChild(scoreLabel, 100); /*add pause button */ pauseBtn = MenuItemImage::create("btn/PauseBtn.png", "btn/PauseBtnSelected.png", CC_CALLBACK_0(PlayScene::pauseGame, this)); pauseBtn->setScale(0.5f); auto pause = Menu::create(pauseBtn, nullptr); pause->setPosition(Vec2(pauseBtn->getContentSize().width, visibleSize.height - pauseBtn->getContentSize().height)); this->addChild(pause); /*add resum button*/ resumeBtn = MenuItemImage::create("btn/PlayBtn.png", "btn/PlayBtnSelected.png", CC_CALLBACK_0(PlayScene::resumeGame, this)); resumeBtn->setScale(0.5f); auto resume = Menu::create(resumeBtn, nullptr); resume->setPosition(Vec2(pauseBtn->getContentSize().width + 50, visibleSize.height / 2)); this->addChild(resume); resumeBtn->setVisible(false); isTouch = false; ableToJump = true; this->setKeyboardEnabled(true); this->scheduleUpdate(); return true; }
void GamePlaying::ImageLayerParse(TMXObjectGroup* og,int& priority ){ if(og==nullptr){ return; } auto objs = og->getObjects(); int assertcount=0; for(auto& obj : objs){ ValueMap& map = obj.asValueMap(); Vec2 pos; std::string type = map["type"].asString(); pos.x=map["x"].asFloat(); pos.y=map["y"].asFloat(); if(type=="cuttable"){ PossesAndUvs pau=GetPolygonVerticesInfo(map); if(!pau.posses.empty()){ ///ポリゴンの生成 MyPolygon p; std::vector<Vec2>& v = p.vertices; for(auto& pos : pau.posses){ v.push_back(pos); } std::vector<Vec2>& uvs=p.uvs; for(auto& uv : pau.uvs){ uvs.push_back(uv); } p.position=pos+pau.center; auto grave=PhysicsBody::createPolygon(&v[0],v.size(),_pm); DrawNodeWithTex* node = DrawNodeWithTex::create(); auto tex=Director::getInstance()-> getTextureCache()-> addImage("soniko.png"); node->SetTexture(tex->getName()); node->drawPolygonT(&v[0],&uvs[0],v.size(),cocos2d::Color4F::YELLOW,0,Color4F::WHITE); node->setPosition(p.position); node->setPhysicsBody(grave); node->setTag(_tag++); p.tag=node->getTag(); p.texId = tex->getName(); p.wasCut=false; _polygons.push_back(p); addChild(node,priority++); } }else if(type=="scaffold"){ Size size; size.width=map["width"].asInt(); size.height=map["height"].asInt(); PhysicsMaterial bm; bm.density=1.0f; bm.friction=0.3f; bm.restitution=0.0f; auto board=PhysicsBody::createBox(size,bm); auto boardnode = Sprite::create("marble.png",Rect(0,0,size.width,size.height)); auto rot = map.find("rotation"); float angle=0; if(rot!=map.end()){ angle = rot->second.asFloat(); } boardnode->setPosition(pos+Vec2(size.width/2,size.height/2).rotate(Vec2::forAngle(-angle*M_PI/180.0f))); boardnode->setPhysicsBody(board); boardnode->setRotation(angle); board->setDynamic(false); addChild(boardnode); } } }
bool MonsterRush::init() { if (!BaseComponent::init()) { return false; } m_Type = OT_MONSTER_RUSH; //물리 초기화 auto meterial = cocos2d::PhysicsMaterial(0, 0, 0); m_Body = cocos2d::PhysicsBody::createBox(cocos2d::Size(RUSH_WIDTH, RUSH_HEIGHT), meterial, cocos2d::Point(0, 0)); m_Body->setContactTestBitmask(PHYC_BLOCK | PHYC_PLAYER | PHYC_MISSILE); m_Body->setCategoryBitmask(PHYC_MONSTER); m_Body->setCollisionBitmask(PHYC_BLOCK | PHYC_FLOOR | PHYC_MISSILE); m_Body->setMass(10); m_Body->setRotationEnable(false); m_Body->setVelocityLimit(1000); m_Body->setVelocity(cocos2d::Vec2(0, 0)); m_Body->setDynamic(true); m_Body->retain(); setPhysicsBody(m_Body); //FSM 초기화 initFSM(1); m_States[0] = STAT_IDLE; m_FSMs[0].resize(STAT_NUM); m_FSMs[0][STAT_IDLE] = nullptr; m_FSMs[0][STAT_MOVE] = move; m_FSMs[0][STAT_KNOCKBACK] = CommonState::knockback; m_Transitions[0].resize(STAT_NUM); m_Transitions[0][STAT_IDLE] = idleTransition; m_Transitions[0][STAT_MOVE] = moveTransition; m_Transitions[0][STAT_KNOCKBACK] = FSM_CALLBACK(MonsterRush::knockbackTransition, this); m_Renders[0].resize(STAT_NUM); m_Renders[0][STAT_IDLE] = GET_COMPONENT_MANAGER()->createComponent<AnimationComponent>(); ( (AnimationComponent*) m_Renders[0][STAT_IDLE] )->setAnimation(AT_MONSTER_RUSH_IDLE, this); m_Renders[0][STAT_MOVE] = GET_COMPONENT_MANAGER()->createComponent<AnimationComponent>(); ( (AnimationComponent*) m_Renders[0][STAT_MOVE] )->setAnimation(AT_MONSTER_RUSH_MOVE, this); m_Renders[0][STAT_KNOCKBACK] = GET_COMPONENT_MANAGER()->createComponent<AnimationComponent>(); ((AnimationComponent*)m_Renders[0][STAT_KNOCKBACK])->setAnimation(AT_MONSTER_RUSH_IDLE, this); for(int i = 0; i < m_Renders[0].size(); i++) { addComponent(m_Renders[0][i]); } //info 설정 auto data = GET_DATA_MANAGER()->getMonsterInfo(OT_MONSTER_RUSH); if (data != nullptr) { m_Info = *GET_DATA_MANAGER()->getMonsterInfo(OT_MONSTER_RUSH); } m_Info.m_CurrentHp = m_Info.m_MaxHp; return true; }
bool HelloWorld::init() { if ( !Layer::init() ) { return false; } this->isGameOver = false; visibleSize = Director::getInstance()->getVisibleSize(); // Ground setup groundSprite0 = Sprite::create("ground.png"); this->addChild(groundSprite0); groundSprite0->setPosition(Vec2(groundSprite0->getContentSize().width/2.0 , groundSprite0->getContentSize().height/2)); groundSprite1 = Sprite::create("ground.png"); this->addChild(groundSprite1); groundSprite1->setPosition(Vec2(visibleSize.width + groundSprite1->getContentSize().width/2.0 -10, groundSprite1->getContentSize().height/2)); auto groundbody0 = PhysicsBody::createBox(groundSprite0->getContentSize()); groundbody0->setDynamic(false); groundbody0->setContactTestBitmask(true); groundSprite0->setPhysicsBody(groundbody0); auto groundbody1 = PhysicsBody::createBox(groundSprite1->getContentSize()); groundbody1->setDynamic(false); groundbody1->setContactTestBitmask(true); groundSprite1->setPhysicsBody(groundbody1); // SkyGround setup Sprite *skySprite0 = Sprite::create("flappy_background.png"); Sprite *skySprite1 = Sprite::create("flappy_background.png"); Sprite *skySprite2 = Sprite::create("flappy_background.png"); this->addChild(skySprite0); this->addChild(skySprite1); this->addChild(skySprite2); skySprite0->setPosition(visibleSize.width/2, 168 + 200); skySprite1->setPosition(visibleSize.width/2 - skySprite1->getContentSize().width, 168 + 200); skySprite2->setPosition(visibleSize.width/2 + skySprite1->getContentSize().width, 168 + 200); // bird setup /* Sprite *birdSprite = Sprite::create("flappybird1.png"); this->addChild(birdSprite); birdSprite->setPosition(visibleSize.width/2, visibleSize.height/2 + 120); */ SpriteFrameCache* cache = SpriteFrameCache::getInstance(); cache->addSpriteFramesWithFile("bird.plist"); auto flyAnim = Animation::create(); for (int i = 1; i < 4; i++) { SpriteFrame * frame = cache->getSpriteFrameByName("flappybird" + to_string(i) + ".png"); flyAnim->addSpriteFrame(frame); } auto birdSprite = Sprite::createWithSpriteFrameName("flappybird1.png"); flyAnim->setDelayPerUnit(0.2f); auto action = Animate::create(flyAnim); auto animation = RepeatForever::create(action); birdSprite->runAction(animation); birdSprite->setPosition(Vec2(visibleSize.width/2, visibleSize.height/2 + 80)); this->addChild(birdSprite); auto birdBody = PhysicsBody::createCircle(17.0); birdBody->setDynamic(true); birdBody->setMass(1.0f); birdBody->setVelocity(Vec2(4.0f, 2.0f)); birdBody->setVelocityLimit(50); birdBody->setContactTestBitmask(true); birdSprite->setPhysicsBody(birdBody); //pipe setup topPipeSprite = Sprite::create("top_pipe.png"); bottomPipeSprite = Sprite::create("bottom_pipe.png"); topPipeSprite->setPosition(visibleSize.width + topPipeSprite->getContentSize().width/2, 600); auto pipebody0 = PhysicsBody::createBox(topPipeSprite->getContentSize()); pipebody0->setDynamic(false); topPipeSprite->setPhysicsBody(pipebody0); pipebody0->setContactTestBitmask(true); auto pipebody1 = PhysicsBody::createBox(bottomPipeSprite->getContentSize()); pipebody1->setDynamic(false); pipebody1->setContactTestBitmask(true); bottomPipeSprite->setPhysicsBody(pipebody1); this->positionBottomPipe(); this->addChild(topPipeSprite); this->addChild(bottomPipeSprite); //setup touch listener auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = [=](Touch *touch, Event *event){ if (!this->isGameOver) { birdBody->applyImpulse(Vec2(0, 90.0f)); } log("touch detected!"); return true; }; //setup collision listener auto plistener = EventListenerPhysicsContact::create(); plistener->onContactBegin = [=](PhysicsContact &contact){ log("collision detected!"); auto gameOverSprite = Sprite::create("game_over.png"); gameOverSprite->setPosition(Vec2(visibleSize.width/2, visibleSize.height/2)); this->addChild(gameOverSprite); this->isGameOver = true; auto restartListner = EventListenerTouchOneByOne::create(); restartListner->setSwallowTouches(true); restartListner->onTouchBegan = [](Touch *touch, Event* event){ Director::getInstance()->replaceScene(HelloWorld::createScene()); return true; }; Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(restartListner, gameOverSprite); return true; }; Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this); Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(plistener, this); this->scheduleUpdate(); return true; }
bool GameLayer::init() { if (!Layer::init()) { return false; } this->score = 0; this->gameStatus = GameStatus::GAME_RUNNING; this->bestScore = UserDefault::getInstance()->getIntegerForKey(KEY); visibleSize = Director::getInstance()->getVisibleSize(); //创建小鸟 this->bird = BirdSprite::getInstance(); this->bird->createBird(); //创建物理属性 PhysicsBody *body = PhysicsBody::createCircle(15); //设置为受到重力影响的动态刚体 body->setDynamic(true); //设置线性阻尼 body->setLinearDamping(0.0f); //设置刚体是否受物理世界重力的影响 body->setGravityEnable(false); //设置形状的恢复系数 //body->getShape(0)->setRestitution(0.0f); body->getShape(0)->setDensity(1.0f); //设置所属种类的掩码值 body->setCategoryBitmask(BIRD_MASK); body->setCollisionBitmask(BIRD_MASK | OBST_MASK); body->setContactTestBitmask(BIRD_MASK | OBST_MASK); this->bird->setPhysicsBody(body); this->bird->setPosition(visibleSize.width / 3, visibleSize.height / 2); this->bird->idle(); this->bird->fly(); this->addChild(this->bird, 2); //添加陆地物理属性 auto land = Node::create(); landHeight = BackgroundLayer::getLandHeight(); auto landBody = PhysicsBody::createBox(Size(visibleSize.width, landHeight)); landBody->getShape(0)->setRestitution(0.0f); landBody->setDynamic(false); landBody->setGravityEnable(false); landBody->setCategoryBitmask(OBST_MASK); landBody->setCollisionBitmask(BIRD_MASK | OBST_MASK); landBody->setContactTestBitmask(BIRD_MASK | OBST_MASK); land->setPhysicsBody(landBody); land->setPosition(visibleSize.width / 2, landHeight / 2); this->addChild(land, 10); //添加碰撞监听 auto contactListener = EventListenerPhysicsContact::create(); contactListener->onContactBegin = CC_CALLBACK_1(GameLayer::onContactBegin, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this); this->createPips(); this->scheduleUpdate(); this->schedule(schedule_selector(GameLayer::scrollPipe), 0.01f); 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 GameScene_Chipmunk::init() { if ( !Scene::init() ) { return false; } //画面サイズサイズを取得 auto window_size = Director::getInstance()->getWinSize(); //床 auto floor = Sprite::create(); floor->setPosition(window_size.width/2, 0); floor->setTextureRect(Rect(0,0,window_size.width,100)); floor->setColor(Color3B(255,255,255)); floor->setTag(spriteType::kFloor); _floor = floor->getSpriteFrame()->getRect(); auto left_wall = Sprite::create(); left_wall->setPosition(10, window_size.height/2); left_wall->setTextureRect(Rect(0,0,10,window_size.height*2)); left_wall->setColor(Color3B(255,255,255)); _leftwall = left_wall->getSpriteFrame()->getRect(); auto right_wall = Sprite::create(); right_wall->setPosition(window_size.width, window_size.height/2); right_wall->setTextureRect(Rect(0,0,10,window_size.height*2)); right_wall->setColor(Color3B(255,255,255)); _rightwall = right_wall->getSpriteFrame()->getRect(); _ceil = Rect(window_size.width/2, window_size.height - 200, window_size.width, 20); //wall->setRotation(10.0f); //反発係数と摩擦係数 auto material = PHYSICSBODY_MATERIAL_DEFAULT; material.restitution = 0.0f; material.friction = 1.0f; auto pWall = PhysicsBody::createBox(floor->getContentSize(), material); //重力干渉を受けるか pWall->setDynamic(false); //回転させるか pWall->setRotationEnable(false); pWall->setContactTestBitmask(true); floor->setPhysicsBody(pWall); addChild(floor); auto pright_wall = PhysicsBody::createBox(right_wall->getContentSize(), material); //重力干渉を受けるか pright_wall->setDynamic(false); //回転させるか pright_wall->setRotationEnable(false); right_wall->setPhysicsBody(pright_wall); addChild(right_wall); auto pleft_wall = PhysicsBody::createBox(left_wall->getContentSize(), material); //重力干渉を受けるか pleft_wall->setDynamic(false); //回転させるか pleft_wall->setRotationEnable(false); left_wall->setPhysicsBody(pleft_wall); addChild(left_wall); //event listener //イベントリスナー作成 auto listener = EventListenerTouchAllAtOnce::create(); //イベントを飲み込むかどうか //listener->setSwallowTouches(true); //タッチメソッド設定 listener->onTouchesBegan = CC_CALLBACK_2(GameScene_Chipmunk::onTouchesBegan, this); listener->onTouchesMoved = CC_CALLBACK_2(GameScene_Chipmunk::onTouchesMoved, this); listener->onTouchesEnded = CC_CALLBACK_2(GameScene_Chipmunk::onTouchesEnded, this); //this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this); //優先度100でディスパッチャーに登録 this->getEventDispatcher()->addEventListenerWithFixedPriority(listener, 100); //衝突検知 auto plistener = EventListenerPhysicsContact::create(); plistener->onContactBegin = CC_CALLBACK_1(GameScene_Chipmunk::onContactBegin, this); this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(plistener, this); auto plistenerend = EventListenerPhysicsContact::create(); plistenerend->onContactPostSolve = CC_CALLBACK_2(GameScene_Chipmunk::onContactPostSolve, this); this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(plistenerend, this); this->fillBoll(); scheduleUpdate(); return true; }
// on "init" you need to initialize your instance bool Practice1::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(Practice1::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... auto label = Label::createWithTTF("練習シーン1", "fonts/07やさしさゴシック.ttf", 24); label->setAnchorPoint(Vec2(0.0f, 0.0f)); label->setPosition(origin.x, origin.y + visibleSize.height); this->addChild(label); nowCount = Label::createWithTTF("現在のカウント: 0", "fonts/07やさしさゴシック.ttf", 24); nowCount->setPosition(origin.x + visibleSize.width/2, origin.y + visibleSize.height/2); this->addChild(nowCount); count = 0; // add this scene to update schedule //this->scheduleUpdate(); //this->schedule(schedule_selector(Practice1::updateByTimer), 1.0f); // create field // 空のスプライトを用意 float fieldWidth = visibleSize.width / 2; float fieldHeight = visibleSize.height + 100.0f; float fieldBlockWidth = fieldWidth / 8; const int fieldObjectNumber = 3; Rect fieldSizes[fieldObjectNumber] = { { 0, 0, fieldBlockWidth, fieldHeight }, { 0, 0, fieldWidth, fieldBlockWidth }, { 0, 0, fieldBlockWidth, fieldHeight }, }; Point fieldPoints[fieldObjectNumber] = { { origin.x + visibleSize.width / 2 - fieldWidth/2 - fieldBlockWidth, origin.x + visibleSize.height }, { origin.x + visibleSize.width / 2 - fieldWidth / 2, origin.x + visibleSize.height }, { origin.x + visibleSize.width / 2 + fieldWidth / 2, origin.x + visibleSize.height }, }; //for (int i = 0; i < fieldObjectNumber; ++i) for (int i = 0; i < 1; ++i) { Sprite* field = Sprite::create("HelloWorld.png"); //Sprite* field = Sprite::create(); //field->setColor(Color3B::WHITE); field->setAnchorPoint(Vec2(0, 1.0)); field->setTextureRect(fieldSizes[i]); field->setPosition(fieldPoints[i]); //auto fieldPhysics = PhysicsBody::createBox(fieldSizes[i].size); auto fieldPhysics = PhysicsBody::createBox(Size(field->getContentSize().width, field->getContentSize().height)); fieldPhysics->setDynamic(false); fieldPhysics->setRotationEnable(false); field->setPhysicsBody(fieldPhysics); this->addChild(field); } auto sprite2 = Sprite::create("EDGE(after).png"); sprite2->setPosition(Vec2(visibleSize.width / 2 + origin.x, visibleSize.height/2 + origin.y)); auto sprite2Physics = PhysicsBody::createBox(Size(sprite2->getContentSize().width, sprite2->getContentSize().height)); sprite2Physics->setDynamic(true); sprite2Physics->setRotationEnable(false); sprite2->setPhysicsBody(sprite2Physics); this->addChild(sprite2); return true; }
Scene* HelloWorld::createScene() { // 'scene' is an autorelease object auto scene = Scene::createWithPhysics(); // 'layer' is an autorelease object auto layer = HelloWorld::create(); // add layer as a child to scene scene->addChild(layer); // 重力の設定. layer->world = scene->getPhysicsWorld(); Vect gravity; gravity.setPoint(0.0f, -1500.0f); layer->world->setGravity(gravity); // layer->world Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); // 地面の描画. auto floor = Sprite::create("Texture/Background.png"); auto backgroundSize = floor->getContentSize(); floor->setPosition(Vec2(visibleSize.width / 2 + origin.x, backgroundSize.height / 2.0f)); layer->addChild(floor, 0); // 地面の物理設定. auto floorPhysicsBody = PhysicsBody::createBox(backgroundSize); floorPhysicsBody->setDynamic(false); floorPhysicsBody->setCategoryBitmask(1); auto dummyPhysicsBody = PhysicsBody::createBox(Size(0, 0)); dummyPhysicsBody->setPositionOffset(floor->getPosition()); dummyPhysicsBody->setDynamic(false); //auto joint = PhysicsJointDistance::construct(floorPhysicsBody, dummyPhysicsBody, floor->getPosition(), Vec2(0, 10)); auto pin = PhysicsJointPin::construct(floorPhysicsBody, dummyPhysicsBody, Vec2(0, 90)); pin->setCollisionEnable(false); floor->setPhysicsBody(floorPhysicsBody); layer->floor = floor; //scene->getPhysicsWorld()->addJoint(pin); for (int i = 0; i < 2; i++) { // ボールの描画. auto ball = Sprite::create("Texture/Ball.png"); layer->ballList.push_back(ball); ball->setPosition(Vec2(visibleSize.width / 2 + origin.x + i * 32, visibleSize.height / 2.0f + i * 256)); // ボールの物理設定. auto ballMaterial = PHYSICSBODY_MATERIAL_DEFAULT; ballMaterial.restitution = 1.5f; ballMaterial.friction = 0.8f; auto ballPhysicsBody = PhysicsBody::createCircle(ball->getContentSize().width / 2.0f, ballMaterial); ballPhysicsBody->setMass(10.0f); ballPhysicsBody->setCollisionBitmask(1); ballPhysicsBody->setCategoryBitmask(2); ball->setPhysicsBody(ballPhysicsBody); layer->addChild(ball, -i); } layer->setTouchMode(kCCTouchesOneByOne); layer->setTouchEnabled(true); // return the scene return scene; }
bool PlayScene::init() { if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); auto height = visibleSize.height; auto width = visibleSize.width; auto background = Sprite::create("res/scr1.png"); background->setPosition(width/2, height/2); background->setScale(102.6); this->addChild(background,0); myplane=Sprite::create("res/plpl.png"); myplane->setPosition(300,300); auto body = PhysicsBody::createBox(Size(70, 40)); body->setMass(1000); myplane->setPhysicsBody(body); addChild(myplane); auto dispatcher = Director::getInstance()->getEventDispatcher(); auto myListener = EventListenerTouchOneByOne::create(); //如果不加入此句消息依旧会向下传递 myListener->setSwallowTouches(true); touchdown = false; float playfield_width = visibleSize.width * 2.0; // make the x-boundry 2 times the screen width float playfield_height = visibleSize.height * 2.0; // make the y-boundry 2 times the screen height Point center = Point(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y); //note : since bounddries are 2 times the screen size calculate new center point // this->runAction(Follow::create(myplane) ); myplane->getPhysicsBody()->setVelocityLimit(200); fire = ParticleSun::create(); fire->setTexture(Director::getInstance()->getTextureCache()->addImage("res/fire.png")); // fire->setGravity(Vec2(-300,0)); addChild(fire); myplane->getPhysicsBody()->getPosition(); myListener->onTouchBegan = [=](Touch* touch,Event* event) { //some check CCLOG("touchbegin"); touchdown = true; if (1) { return true; } return false; }; for (int i = 0; i<0; i++) { auto x = arc4random()%(int)width; auto y = arc4random()%(int)height; Sprite* rock = Sprite::create("res/debris.png"); rock->setPosition(x,y); rock->setScale(0.3); addChild(rock); rock->setPosition(x,y); auto rockbody = PhysicsBody::createCircle(30); // rockbody->setDynamic(false); auto vx =arc4random()%300; auto vy =arc4random()%300; // rockbody->setVelocity(Vec2(vx-150,vy-150)); rockbody->setMass(1000); rock->setPhysicsBody(rockbody); } myListener->onTouchMoved = [=](Touch* touch,Event* event) { }; myListener->onTouchEnded = [=](Touch* touch,Event* event) { touchdown = false; auto angle = myplane->getPhysicsBody()->getRotation(); auto angle1 = (angle+0) /180*M_PI; auto angle2 = (angle+90) /180*M_PI; // myplane->getPhysicsBody()->applyForce(Vec2(-600000*cos(angle1),-600000*sin(angle1))); // myplane->getPhysicsBody()->applyForce(Vec2(-400000*cos(angle2),-400000*sin(angle2))); myplane->getPhysicsBody()->resetForces(); }; dispatcher->addEventListenerWithSceneGraphPriority(myListener,this); auto edgeSp = Sprite::create(); auto body2 = PhysicsBody::createEdgeBox(Size(visibleSize.width*30,visibleSize.height)); edgeSp->setPosition(Point(visibleSize.width/2,visibleSize.height/2)); edgeSp->setPhysicsBody(body2); this->addChild(edgeSp); edgeSp->setTag(0); scheduleUpdate(); return true; }
bool GameMap::init() { if(!Node::init()) return false; //Ìí¼Óש¿é std::string block_file; std::string npc_file; switch(level) { case SPRING: block_file="block_spring.png"; npc_file="lvshuiling.png"; break; case WINTER: block_file="block_winter.png"; npc_file="lanmogu.png"; break; } std::string star_file="star.png"; std::string tool_file="accelerate.png"; //ÊÖ¶¯´î½¨µØͼ£¬Ã»ÓмÓÈ뼴ʱ¼ÆËã~ //1²ã for(int i=0;i<10;i++) { if(i!=3&&i!=4&&i!=7&&i!=8) { //Ìí¼Óland auto block=Sprite::create(block_file); block->setPosition(BLOCK_SIZE/2+i*BLOCK_SIZE,BLOCK_SIZE/2+1*BLOCK_SIZE); this->addChild(block); block->setTag(LAND); //ÉèÖÃtag auto blockBody=PhysicsBody::createBox(block->getContentSize()); blockBody->setDynamic(false); blockBody->setContactTestBitmask(1); blockBody->getShape(0)->setRestitution(0); block->setPhysicsBody(blockBody); } } //2²ã for(int i=0;i<10;i++) { if(i==2||i==5||i==6) { //Ìí¼Ó¹ÖÎï auto npc=Sprite::create(npc_file); npc->setTag(NPC); npc->setPosition(BLOCK_SIZE/2+i*BLOCK_SIZE,BLOCK_SIZE/2+2*BLOCK_SIZE); auto npcBody=PhysicsBody::createBox(npc->getContentSize()); npcBody->setDynamic(false); npcBody->setContactTestBitmask(1); npcBody->getShape(0)->setRestitution(0); npc->setPhysicsBody(npcBody); this->addChild(npc); } if(i==3) { //Ìí¼Óland auto block=Sprite::create(block_file); block->setPosition(BLOCK_SIZE/2+i*BLOCK_SIZE,BLOCK_SIZE/2+1*BLOCK_SIZE); this->addChild(block); block->setTag(LAND); //ÉèÖÃtag auto blockBody=PhysicsBody::createBox(block->getContentSize()); blockBody->setDynamic(false); blockBody->setContactTestBitmask(1); blockBody->getShape(0)->setRestitution(0); block->setPhysicsBody(blockBody); } } //3²ã for(int i=0;i<10;i++) { if(i!=0&&i!=3&&i!=4) { //Ìí¼ÓÐÇÐÇ auto star1=Sprite::create(star_file); star1->setTag(STAR); star1->setPosition(PICKUP_SIZE/2+i*BLOCK_SIZE,BLOCK_SIZE/2+3*BLOCK_SIZE); auto starBody1=PhysicsBody::createBox(star1->getContentSize()); starBody1->setDynamic(false); starBody1->setContactTestBitmask(1); starBody1->getShape(0)->setRestitution(0.0f); star1->setPhysicsBody(starBody1); this->addChild(star1); auto star2=Sprite::create(star_file); star2->setTag(STAR); star2->setPosition(PICKUP_SIZE/2*3+i*BLOCK_SIZE,BLOCK_SIZE/2+3*BLOCK_SIZE); auto starBody2=PhysicsBody::createBox(star2->getContentSize()); starBody2->setDynamic(false); starBody2->setContactTestBitmask(1); starBody2->getShape(0)->setRestitution(0.0f); star2->setPhysicsBody(starBody2); this->addChild(star2); } } //4²ã for(int i=0;i<10;i++) { if(i==3||i==4) { //Ìí¼Óland auto block=Sprite::create(block_file); block->setPosition(BLOCK_SIZE/2+i*BLOCK_SIZE,BLOCK_SIZE/2+4*BLOCK_SIZE); this->addChild(block); block->setTag(LAND); //ÉèÖÃtag auto blockBody=PhysicsBody::createBox(block->getContentSize()); blockBody->setDynamic(false); blockBody->setContactTestBitmask(1); blockBody->getShape(0)->setRestitution(0); block->setPhysicsBody(blockBody); } if(i==8) { auto star1=Sprite::create(star_file); star1->setTag(STAR); star1->setPosition(PICKUP_SIZE/2+i*BLOCK_SIZE,BLOCK_SIZE/2+3*BLOCK_SIZE); auto starBody1=PhysicsBody::createBox(star1->getContentSize()); starBody1->setDynamic(false); starBody1->setContactTestBitmask(1); starBody1->getShape(0)->setRestitution(0.0f); star1->setPhysicsBody(starBody1); this->addChild(star1); auto star2=Sprite::create(star_file); star2->setTag(STAR); star2->setPosition(PICKUP_SIZE/2*3+i*BLOCK_SIZE,BLOCK_SIZE/2+3*BLOCK_SIZE); auto starBody2=PhysicsBody::createBox(star2->getContentSize()); starBody2->setDynamic(false); starBody2->setContactTestBitmask(1); starBody2->getShape(0)->setRestitution(0.0f); star2->setPhysicsBody(starBody2); this->addChild(star2); } if(i==6) { //Ìí¼ÓµÀ¾ß auto tool=Sprite::create(tool_file); tool->setTag(TOOL); tool->setPosition(PICKUP_SIZE/2+i*BLOCK_SIZE,BLOCK_SIZE/2+3*BLOCK_SIZE); auto toolBody=PhysicsBody::createBox(tool->getContentSize()); toolBody->setDynamic(false); toolBody->setContactTestBitmask(1); toolBody->getShape(0)->setRestitution(0.0f); tool->setPhysicsBody(toolBody); this->addChild(tool); } } //Æô¶¯µ÷¶ÈÆ÷£¬µØͼ¹öÆÁ this->schedule(schedule_selector(GameMap::mapUpdate),0.01f); 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); } } }
// on "init" you need to initialize your instance bool GameSceneQuattro::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } _visibleSize = Director::getInstance()->getVisibleSize(); _origin = Director::getInstance()->getVisibleOrigin(); //definisco le pallina che lancia Gugut _pietre = new Vector<Sprite*>(20); for (int i = 0; i < 19; ++i) { auto *pietra = Sprite::create("pietra.png"); pietra->setVisible(false); pietra->setTag(PIETRA_TAG); this->addChild(pietra, 11); _pietre->pushBack(pietra); } #define MUMEROPALLINE 5 _palline = new Vector<PallinaSprite*>(MUMEROPALLINE); char strPallina[100] = {0}; for (int i = 2; i < 6; ++i) { sprintf(strPallina, "sfera_%02d.png",i); //da 02 .. 05 totale 4 palline auto *pallina = PallinaSprite::pallinaSpriteWithFile(strPallina); pallina->setVisible(true); pallina->setTag(i); if(i == 2){ auto spriteBody = PhysicsBody::createCircle(pallina->getContentSize().width/2, PhysicsMaterial(1.0f, 1.0f, 0.1f)); spriteBody->setCollisionBitmask(3); spriteBody->setContactTestBitmask(true); pallina->setPhysicsBody( spriteBody ); pallina->setPosition(Vec2( _visibleSize.width / 2 + _origin.x, _visibleSize.height / 2 + _origin.y )); spriteBody->setTag(12); pallina->setPunti(10); } if(i == 3){ auto spriteBody = PhysicsBody::createCircle(pallina->getContentSize().width/2, PhysicsMaterial(0.05f, 1.0f, 0.1f)); spriteBody->setCollisionBitmask(3); spriteBody->setContactTestBitmask(true); pallina->setPhysicsBody( spriteBody ); pallina->setPosition(Vec2( _visibleSize.width / 3 + _origin.x, _visibleSize.height / 3 + _origin.y )); spriteBody->setTag(13); pallina->setPunti(10); } if(i == 4){ auto spriteBody = PhysicsBody::createCircle(pallina->getContentSize().width/2, PhysicsMaterial(0.95f, 1.0f, 0.1f)); spriteBody->setCollisionBitmask(3); spriteBody->setContactTestBitmask(true); pallina->setPhysicsBody( spriteBody ); pallina->setPosition(Vec2( _visibleSize.width / 4 + _origin.x, _visibleSize.height / 2 + _origin.y )); spriteBody->setTag(14); pallina->setPunti(10); } if(i == 5){ auto spriteBody = PhysicsBody::createCircle(pallina->getContentSize().width/2, PhysicsMaterial(0.05f, 0.9f, 0.9f)); spriteBody->setCollisionBitmask(3); spriteBody->setContactTestBitmask(true); pallina->setPhysicsBody( spriteBody ); pallina->setPosition(Vec2( _visibleSize.width * 0.8 + _origin.x, _visibleSize.height / 2 + _origin.y )); spriteBody->setTag(15); pallina->setPunti(10); } this->addChild(pallina, 9); _palline->pushBack(pallina); //applico forza // if(i == 4) // pallina->getPhysicsBody()->applyForce( Vect(100, 78) ); // if(i == 5) // pallina->getPhysicsBody()->applyForce( Vect(200, 78) ); } _muro = Sprite::create("muro.png"); _muro->setAnchorPoint(Vec2(0.0, 0.0)); _muro->setPosition(Vec2(_origin.x, _origin.y)); this->addChild(_muro, 6); //Gugut _gugutAnimato = Sprite::create("gugut_01.png"); _gugutAnimato->setVisible(true); _gugutAnimato->setAnchorPoint(Vec2(0.5, 0.2));//+(_muro->getContentSize().height )+(_gugutAnimato->getContentSize().height ) //_gugutAnimato->setPosition(Vec2(_muro->getContentSize().width/2 + origin.x, (_muro->getContentSize().height * 1.45)+ origin.y)); _gugutAnimato->setPosition(Vec2(_muro->getContentSize().width/2 + _origin.x,(_muro->getContentSize().height )+ _origin.y)); this->addChild(_gugutAnimato, 8); auto edgeBody = PhysicsBody::createEdgeBox( _visibleSize, PHYSICSBODY_MATERIAL_DEFAULT, 3 ); auto edgeNode = Node::create(); edgeNode ->setPosition( Point( _visibleSize.width / 2 + _origin.x, _visibleSize.height / 2 + _origin.y ) ); edgeNode->setPhysicsBody( edgeBody ); this->addChild( edgeNode ); auto contactListener = EventListenerPhysicsContact::create(); contactListener->onContactBegin = CC_CALLBACK_1(GameSceneQuattro::onContactBegin, this); this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(contactListener, this); auto dispatcher = Director::getInstance()->getEventDispatcher(); auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = CC_CALLBACK_2(GameSceneQuattro::onTouchBegan, this); listener->onTouchMoved = CC_CALLBACK_2(GameSceneQuattro::onTouchMoved, this); dispatcher->addEventListenerWithSceneGraphPriority(listener, this); addPartcleStella(Vec2(0,0)); Sprite* parent = Sprite::create("unpixel.png"); parent->setTextureRect(CCRectMake(0,0, 400, 200)); parent->setColor(ccc3(255,0, 0)); parent->setAnchorPoint(Vec2(0,0)); parent->setPosition(Vec2( _visibleSize.width / 2 + _origin.x, _visibleSize.height / 2 + _origin.y)); auto edgeBody2 = PhysicsBody::createBox( parent->getContentSize( ), PHYSICSBODY_MATERIAL_DEFAULT, Vec2(0,0) ); edgeBody2->setDynamic(false); parent->setPhysicsBody( edgeBody2 ); this->addChild(parent, 20); return true; }
bool MonsterDevil::init() { if (!BaseComponent::init()) { return false; } m_Type = OT_MONSTER_DEVIL; m_PathFinder = new PathFinderByBFS(); ////info 설정 auto data = GET_DATA_MANAGER()->getMonsterInfo(OT_MONSTER_DEVIL); if (data != nullptr) { m_Info = *GET_DATA_MANAGER()->getMonsterInfo(OT_MONSTER_DEVIL); } m_Info.m_CurrentHp = m_Info.m_MaxHp; //물리 초기화 auto meterial = cocos2d::PhysicsMaterial(0, 0, 0); m_Body = cocos2d::PhysicsBody::createBox(cocos2d::Size(m_Info.m_Size.width, m_Info.m_Size.height), meterial, cocos2d::Point(0, 0)); m_Body->setContactTestBitmask(PHYC_BLOCK | PHYC_PLAYER | PHYC_MISSILE | PHYC_FLOOR); m_Body->setCategoryBitmask(PHYC_MONSTER); m_Body->setCollisionBitmask(PHYC_BLOCK | PHYC_MISSILE); m_Body->setMass(10); m_Body->setRotationEnable(false); m_Body->setVelocityLimit(1000); m_Body->setVelocity(cocos2d::Vec2(0, 0)); m_Body->setDynamic(true); m_Body->setGravityEnable(false); m_Body->retain(); setPhysicsBody(m_Body); initFSM(1); m_States[0] = STAT_IDLE; m_FSMs[0].resize(STAT_NUM); m_FSMs[0][STAT_IDLE] = nullptr; m_FSMs[0][STAT_MOVE] = FSM_CALLBACK(MonsterDevil::move, this); m_FSMs[0][STAT_READYATTACK] = FSM_CALLBACK(MonsterDevil::readyAttack, this); m_FSMs[0][STAT_ATTACK] = FSM_CALLBACK(MonsterDevil::attack, this); m_Transitions[0].resize(STAT_NUM); m_Transitions[0][STAT_IDLE] = FSM_CALLBACK(MonsterDevil::idleTransition, this); m_Transitions[0][STAT_MOVE] = FSM_CALLBACK(MonsterDevil::moveTransition, this); m_Transitions[0][STAT_READYATTACK] = FSM_CALLBACK(MonsterDevil::readyAttackTransition, this); m_Transitions[0][STAT_ATTACK] = FSM_CALLBACK(MonsterDevil::attackTransition, this); m_Renders[0].resize(STAT_NUM); m_Renders[0][STAT_IDLE] = GET_COMPONENT_MANAGER()->createComponent<AnimationComponent>(); ((AnimationComponent*)m_Renders[0][STAT_IDLE])->setAnimation(AT_DEVIL_IDLE, this); m_Renders[0][STAT_MOVE] = GET_COMPONENT_MANAGER()->createComponent<AnimationComponent>(); ((AnimationComponent*)m_Renders[0][STAT_MOVE])->setAnimation(AT_DEVIL_MOVE, this); m_Renders[0][STAT_READYATTACK] = GET_COMPONENT_MANAGER()->createComponent<AnimationComponent>(); ((AnimationComponent*)m_Renders[0][STAT_READYATTACK])->setAnimation(AT_DEVIL_IDLE, this); m_Renders[0][STAT_ATTACK] = GET_COMPONENT_MANAGER()->createComponent<AnimationComponent>(); ((AnimationComponent*)m_Renders[0][STAT_ATTACK])->setAnimation(AT_DEVIL_ATTACK, this, 1, true); for (unsigned int i = 0; i < m_Renders[0].size(); i++) { addComponent(m_Renders[0][i]); } //arrow 설정 m_ArrowAniComponent = GET_COMPONENT_MANAGER()->createComponent<AnimationComponent>(); m_ArrowAniComponent->setAnimation(AT_DEVIL_ARROW, this, 2, true); addComponent(m_ArrowAniComponent); return true; }
bool FruitCutNinjaScene::init() { if (!Layer::init()) { return false; } _visibleSize = Director::getInstance()->getVisibleSize(); _deltaRemainder = 0.0f; _sliceTag = 1; //createBackground(); //加入封闭的盒子,用作墙壁 auto body = PhysicsBody::createEdgeBox(_visibleSize, PHYSICSBODY_MATERIAL_DEFAULT, 3); auto wallNode = Node::create(); wallNode->setPosition(_visibleSize.width/2, _visibleSize.height/2); wallNode->setPhysicsBody(body); this->addChild(wallNode); auto touchListener = EventListenerTouchAllAtOnce::create(); touchListener->onTouchesBegan = CC_CALLBACK_2(FruitCutNinjaScene::onTouchesBegan, this); touchListener->onTouchesMoved = CC_CALLBACK_2(FruitCutNinjaScene::onTouchesMoved, this); touchListener->onTouchesEnded = CC_CALLBACK_2(FruitCutNinjaScene::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); auto texture = Director::getInstance()->getTextureCache()->addImage("streak.png"); for (int i = 0; i < 3; i++) { Blade* blade = Blade::createWithMaximumPoint(50); blade->setAutoDim(false); blade->setTexture(texture); addChild(blade, 100); _blades.pushBack(blade); } //PEShapeCache::getInstance()->addBodysWithFile("pineapple.plist"); //auto body = PEShapeCache::getInstance()->getPhysicsBodyByName("pineapple"); //Point points[4] = {Point(-128 + 128, -128 + 128), Point(-128 + 128, 128 + 128), Point(128 + 128, 128 + 128), Point(128 + 128, -128 + 128)}; /* Point points[9] = { Point(157,50), Point(119, 13), Point(54, 0), Point(7,36), Point(5, 78), Point(23,118), Point(170,252), Point(235, 244), Point(237,158) }; */ Point points[4] = { Point(0, 0), Point(0, 512), Point(512, 512), Point(512, 0) }; Vector2dVector vcPoints; vcPoints.clear(); for (int i = 0; i < 4; i++) { vcPoints.push_back(Vector2d(points[i].x, points[i].y)); } //texture = Director::getInstance()->getTextureCache()->addImage("boluo.png"); PRFilledPolygon *filledPolygon = PRFilledPolygon::filledPolygonWithPointsAndTexture(vcPoints, "boluo.png"); filledPolygon->setPhysicsBody(PhysicsBody::createPolygon(points, 4)); filledPolygon->setPosition(Vec2(400, 700)); filledPolygon->getPhysicsBody()->setTag(_sliceTag); filledPolygon->getPhysicsBody()->setGravityEnable(false); addChild(filledPolygon, 80); filledPolygon = PRFilledPolygon::filledPolygonWithPointsAndTexture(vcPoints, "xigua.png"); filledPolygon->setPhysicsBody(PhysicsBody::createPolygon(points, 4)); filledPolygon->setPosition(Vec2(1200, 700)); filledPolygon->getPhysicsBody()->setTag(_sliceTag); filledPolygon->getPhysicsBody()->setGravityEnable(false); addChild(filledPolygon, 80); for (int i = 0; i < PARTICLE_COUNT; i++) { m_pEmitter[i] = ParticleSystemQuad::create("pineapple_splurt.plist"); this->addChild(m_pEmitter[i], 100); m_pEmitter[i]->setAutoRemoveOnFinish(false); m_pEmitter[i]->setDuration(0.1f); m_pEmitter[i]->setScale(1.5f); } //本DEMO要做成一个切水果原型,尚未完成:) scheduleUpdate(); return true; }
// on "init" you need to initialize your instance bool GameScene::init() { ////////////////////////////// // 1. super init first if (!Layer::init()) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic("Sounds/BKGMusic.mp3", true); //create a background for game //for testing on pc //auto backgroundSprite = Sprite::create("C:\\Users\\Kyle\\Documents\\GitHub\\GetToTheLander\\Resources\\iphone\\GameBackground.png"); //for platform: auto backgroundSprite = Sprite::create("GameBackground.png"); backgroundSprite->setPosition(Point(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y)); this->addChild(backgroundSprite); //create body to colide and remove objects from going off screen auto alienSize = Sprite::create("Alien.png"); auto edgeBody = PhysicsBody::createBox(visibleSize, PHYSICSBODY_MATERIAL_DEFAULT); edgeBody->setCollisionBitmask(EDGE_COLLISION_BITMASK); edgeBody->setDynamic(true); edgeBody->setContactTestBitmask(true); auto edgeNode = Node::create(); edgeNode->setPosition(Point((0 - visibleSize.width / 2 + (alienSize->getContentSize().width / 2)) /*- (Sprite::create("Pipe.png")->getContentSize().width)*/, visibleSize.height / 2 + origin.y)); this->addChild(backgroundSprite); edgeNode->setPhysicsBody(edgeBody); this->addChild(edgeNode); auto alienSprite = Sprite::create("Alien.png"); alienSprite->setPosition(Point(origin.x, visibleSize.height / 3 + origin.y)); this->addChild(alienSprite, 100); //spawn Rocks based on screen size this->schedule(schedule_selector(GameScene::SpawnRocks), ROCKS_SPAWN_FREQUENCY * visibleSize.width); //spawn pipes based on screen size this->schedule(schedule_selector(GameScene::SpawnPipe), PIPE_SPAWN_FREQUENCY * visibleSize.width); //spawn Mights based on screen size this->schedule(schedule_selector(GameScene::SpawnMights), MIGHTS_SPAWN_FREQUENCY * visibleSize.width); //initialize bird bird = new Bird(this); //add listener for contact auto contactListener = EventListenerPhysicsContact::create(); contactListener->onContactBegin = CC_CALLBACK_1(GameScene::onContactBegin, this); Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(contactListener, this); score = 0; //create a string to hold the running score in cocos library (auto could work) __String *tempScore = __String::createWithFormat("%i", score); scoreLabel = Label::createWithTTF(tempScore->getCString(), "fonts/Marker Felt.ttf", visibleSize.height * SCORE_FONT_SIZE); scoreLabel->setColor(Color3B::WHITE); //set score position scoreLabel->setPosition(Point(visibleSize.width / 2 + origin.x, visibleSize.height * 0.75 + origin.y)); //high value denotes forward position this->addChild(scoreLabel, 10000); //add listener for touch auto touchListener = EventListenerTouchOneByOne::create(); touchListener->setSwallowTouches(true); //number of param is calback number touchListener->onTouchBegan = CC_CALLBACK_2(GameScene::onTouchBegan, this); Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(touchListener, this); this->scheduleUpdate(); return true; }
void Game::setUI(){ //测试在界面上放置组件 Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); // auto gameLabel=Label::createWithTTF("GAME", "fonts/Marker Felt.ttf", 24); // gameLabel->setPosition(Vec2(origin.x + visibleSize.width/2, // origin.y + visibleSize.height - gameLabel->getContentSize().height)); // this->addChild(gameLabel); auto image1=MenuItemImage::create("01.jpg", "01.jpg"); image1->setPosition(100, 100); auto menu=Menu::create(image1,NULL); menu->setPosition(100,100); // this->addChild(menu,1); //下面 测试节点的运动 // auto moveTo=MoveTo::create(3.0f, Vec2(origin.x + visibleSize.width/2, // origin.y + visibleSize.height - gameLabel->getContentSize().height-200)); //auto action=Sequence::create(moveTo,Spawn::create(RotateBy::create(1.0f,360),ScaleTo::create(1.0f,1.2f),NULL),Blink::create(1,5),FadeOut::create(0.5f), NULL); //image1->runAction(action); //下面测试动画的实现 //下面测试触控 // sprite=CCSprite::create("03.jpg"); // sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); // sprite->setScale(1, 0.5); auto sprite1=Sprite::create("00.jpg"); sprite1->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); auto wallBody1=PhysicsBody::createBox(sprite1->getContentSize()); CCLOG("%f,%f",sprite1->getContentSize().width,sprite1->getContentSize().height); wallBody1->setGravityEnable(false); // wallBody1->getShape(0)->setRestitution(1.0f); // wallBody1->getShape(0)->setFriction(0.0); // wallBody1->getShape(0)->setDensity(1.0); // Vect force = Vect(500000.0f, 500000.0f); // wallBody1->applyImpulse(force); wallBody1->setContactTestBitmask(0xFFFFFFFF); sprite1->setPhysicsBody(wallBody1); sprite1->setTag(1); this->addChild(sprite1); auto sprite2=Sprite::create("01.jpg"); sprite2->setPosition(Vec2(300 , 250)); auto wallBody2=PhysicsBody::createBox(sprite2->getContentSize()); wallBody2->setGravityEnable(false); wallBody2->setContactTestBitmask(0xFFFFFFFF); sprite2->setPhysicsBody(wallBody2); sprite2->setTag(2); this->addChild(sprite2); sprite2->runAction(MoveTo::create(2, Vec2(400, 400))); Sprite* edgeSpace=Sprite::create(); PhysicsBody* boundBody=PhysicsBody::createEdgeBox(visibleSize,PHYSICSBODY_MATERIAL_DEFAULT,3); boundBody->getShape(0)->setFriction(0.0f); boundBody->getShape(0)->setRestitution(1.0f); edgeSpace->setPhysicsBody(boundBody); edgeSpace->setPosition(Point(visibleSize.width/2,visibleSize.height/2)); this->addChild(edgeSpace); edgeSpace->setTag(0); auto listener=EventListenerTouchOneByOne::create(); listener->onTouchMoved=CC_CALLBACK_2(Game::onTouchMoved, this); listener->onTouchBegan=CC_CALLBACK_2(Game::onTouchBegan, this); listener->onTouchEnded=CC_CALLBACK_2(Game::onTouchEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); //下面检测碰撞 }
void Tube::spawnTube(cocos2d::Layer *layer){ CCLOG("SPAWN TUBE"); auto topTube = Sprite::create("top_tube.png"); auto bottomTube = Sprite::create("down_tube.png"); auto topTubeBody = PhysicsBody::createBox(topTube->getContentSize()); auto bottomTubeBody = PhysicsBody::createBox(bottomTube->getContentSize()); topTubeBody->setDynamic(false); bottomTubeBody->setDynamic(false); topTubeBody->setCollisionBitmask(OBSTACLE_COLLISION_BITMASK); bottomTubeBody->setCollisionBitmask(OBSTACLE_COLLISION_BITMASK); topTubeBody->setContactTestBitmask(true); bottomTubeBody->setContactTestBitmask(true); topTube->setPhysicsBody(topTubeBody); bottomTube->setPhysicsBody(bottomTubeBody); auto random = CCRANDOM_0_1(); // if(random < LOWER_SCREEN_TUBE_THRESHOLD){ // random = LOWER_SCREEN_TUBE_THRESHOLD; // }else if(random > UPPER_SCREEN_TUBE_THRESHOLD){ // random = UPPER_SCREEN_TUBE_THRESHOLD; // } // auto topTubePosition = ( random * visibleSize.height) + (topTube->getContentSize().height / 2) ; topTube->setPosition(Point( visibleSize.width + topTube->getContentSize().width + origin.x, topTubePosition)); bottomTube->setPosition(Point( topTube->getPositionX(), topTubePosition - (Sprite::create("bird1.png")->getContentSize().height * TUBE_GAP) - topTube->getContentSize().height) ); layer->addChild(topTube); layer->addChild(bottomTube); auto topTubeAction = MoveBy::create(TUBE_MOVEMENT_SPEED * visibleSize.width,Point(-visibleSize.width * 1.5, 0 )); auto bottomTubeAction = MoveBy::create(TUBE_MOVEMENT_SPEED * visibleSize.width,Point(-visibleSize.width * 1.5, 0 )); topTube->runAction(topTubeAction); bottomTube->runAction(bottomTubeAction); auto pointNode = Node::create(); auto pointBody = PhysicsBody::createBox(Size(1,visibleSize.height * 3)); pointBody->setDynamic(false); pointBody->setCollisionBitmask(POINT_COLLISION_BITMASK); pointBody->setContactTestBitmask(true); pointNode->setPhysicsBody(pointBody); pointNode->setPosition(Vec2( topTube->getPositionX(), topTube->getPositionY() - (topTube->getContentSize().height / 2) - ( (Sprite::create("bird1.png")->getContentSize().height * TUBE_GAP ) / 2))); layer->addChild(pointNode); auto pointNodeAction = MoveBy::create(TUBE_MOVEMENT_SPEED * visibleSize.width,Point(-visibleSize.width * 1.5, 0 )); pointNode->runAction(pointNodeAction); }
void GamePlaying::onTouchEnded(Touch* t,Event* ev){ if(_slushLimit==0){ return; } auto stigma = getChildByName("stigma"); stigma->setName(""); stigma->runAction(Sequence::createWithTwoActions(FadeOut::create(0.5f),RemoveSelf::create())); //CreateSlushParticle(_touchedPos,t->getLocation()); bool flg=false; ///カットチェック for(MyPolygon& p : _polygons){ auto nnode = getChildByTag(p.tag); if(nnode==nullptr){ continue; } auto psp=(MyPhysicsShape*)(nnode->getPhysicsBody()->getFirstShape()); auto cps=(cpPolyShape*)(psp->getPolyShape()); auto& polyPos = getChildByTag(p.tag)->getPosition(); for(int j=0;j<cps->numVerts;++j){ if(j==cps->numVerts-1){ flg=IsIntersected(_touchedPos, t->getLocation(), Vec2(cps->tVerts[j].x,cps->tVerts[j].y), Vec2(cps->tVerts[0].x,cps->tVerts[0].y)); if(flg){ PosUv posuv; posuv.pos = IntersectedPoint(_touchedPos, t->getLocation(), Vec2(cps->tVerts[j].x,cps->tVerts[j].y), Vec2(cps->tVerts[0].x,cps->tVerts[0].y)); //とりあえずvertsのインデックスとp.vertices,p.uvsのインデクスが同一であると仮定する。 posuv.uv = GetMidUV(Vec2(cps->verts[j].x,cps->verts[j].y)+polyPos, p.uvs[j], Vec2(cps->tVerts[0].x,cps->tVerts[0].y), p.uvs[0], posuv.pos); p.cutEdges.push_back(std::make_pair(j,posuv));//インデックスとuv&posのペア p.wasCut=true; } }else{ flg=IsIntersected(_touchedPos, t->getLocation(), Vec2(cps->tVerts[j].x,cps->tVerts[j].y), Vec2(cps->tVerts[j+1].x,cps->tVerts[j+1].y)); if(flg){ PosUv posuv; posuv.pos =IntersectedPoint(_touchedPos, t->getLocation(), Vec2(cps->tVerts[j].x,cps->tVerts[j].y), Vec2(cps->tVerts[j+1].x,cps->tVerts[j+1].y)); //とりあえずvertsのインデックスとp.vertices,p.uvsのインデクスが同一であると仮定する。 posuv.uv = GetMidUV(Vec2(cps->tVerts[j].x,cps->tVerts[j].y), p.uvs[j], Vec2(cps->tVerts[j+1].x,cps->tVerts[j+1].y), p.uvs[j+1], posuv.pos); p.cutEdges.push_back(std::make_pair(j,posuv)); p.wasCut=true; } } } } std::vector<Vec2> cuttingEdges; ///一時的…追加用ベクタ作成 std::vector<MyPolygon> addedpolygons(0); int cutcount=0; ///分離処理(頂点の生成) for(MyPolygon& p : _polygons){ if(p.cutEdges.empty() || p.cutEdges.size()==1){//カットできてない場合は次へ p.wasCut=false; p.cutEdges.clear(); continue; } ++cutcount; //n番目がカットされている場合、nとn+1の間をカットしている //カットされている場合は2つのカットポイントが存在する Vec2& fpos=p.cutEdges[0].second.pos; Vec2& spos=p.cutEdges[1].second.pos; if((_touchedPos-fpos).length()>(_touchedPos-spos).length()){ //切るエフェクトの発生 CreateSlushParticle(spos,fpos); }else{ //切るエフェクトの発生 CreateSlushParticle(fpos,spos); } //とりあえず複製を一つ用意する //頂点数も変わる。エッジ番号の差が1なら残りの頂点数は1つまり差=残り頂点数となる //↑2つが新たな頂点となる(ソートが必要) if(p.cutEdges[0].first > p.cutEdges[1].first){ std::swap(p.cutEdges[0],p.cutEdges[1]); } auto nnode = getChildByTag(p.tag); auto& polyPos = nnode->getPosition(); auto psp=(MyPhysicsShape*)(nnode->getPhysicsBody()->getFirstShape()); auto cps=(cpPolyShape*)(psp->getPolyShape()); //sort完了 //差を算出 int diff = p.cutEdges[1].first-p.cutEdges[0].first; Vec2 pos=p.position; MyPolygon poly; std::vector<Vec2>& tmpUvs=p.uvs; poly.vertices.clear(); poly.uvs.clear(); poly.tag = p.tag; poly.texId = p.texId; poly.wasCut=p.wasCut; Vec2 newpos = p.cutEdges[0].second.pos-polyPos; poly.vertices.push_back(newpos); poly.uvs.push_back(p.cutEdges[0].second.uv);//切断端点 for(int i=1;i<=diff;++i){ int idx=p.cutEdges[0].first+i; cpVect& ve=cps->tVerts[idx];//元の座標を利用 newpos = Vec2(ve.x,ve.y)-polyPos; poly.vertices.push_back(newpos); poly.uvs.push_back(tmpUvs[idx]); } newpos = p.cutEdges[1].second.pos-polyPos; poly.vertices.push_back(newpos); poly.uvs.push_back(p.cutEdges[1].second.uv);//切断端点 poly.position = polyPos; addedpolygons.push_back(poly); poly.vertices.clear(); poly.uvs.clear(); //もうひとつのポリゴン diff=p.vertices.size()-diff; poly.texId = p.texId; poly.wasCut=p.wasCut; newpos = p.cutEdges[1].second.pos-polyPos; poly.vertices.push_back(newpos); poly.uvs.push_back(p.cutEdges[1].second.uv);//切断端点 for(int i=1;i<=diff;++i){ int idx = (p.cutEdges[1].first+i)%p.vertices.size(); cpVect& ve=cps->tVerts[idx];//元の座標を利用 newpos = Vec2(ve.x,ve.y)-polyPos; poly.vertices.push_back(newpos); poly.uvs.push_back(tmpUvs[idx]); } newpos = p.cutEdges[0].second.pos-polyPos; poly.vertices.push_back(newpos); poly.uvs.push_back(p.cutEdges[0].second.uv);//切断端点 poly.position = polyPos; addedpolygons.push_back(poly); } //切れてなければリターンする if(cutcount==0){ removeChild(stigma); return; } for(auto& p : _polygons){ auto node = getChildByTag(p.tag); if(node==nullptr){ continue; } auto& polyPos = node->getPosition(); if(!p.wasCut){ p.position=polyPos; } } //切れてしまっている奴は、別の2つに生まれ変わっているので、元のは消す。 for(auto& p : _polygons){ if(p.wasCut){ removeChild(getChildByTag(p.tag)); } } class IFunction{ public: bool operator()(MyPolygon& a){ return a.wasCut; } }; _polygons.erase(std::remove_if(_polygons.begin(),_polygons.end(),IFunction()),_polygons.end()); std::copy(addedpolygons.begin(),addedpolygons.end(),std::back_inserter(_polygons)); ///実際のポリゴン生成 for(auto& pl : _polygons){ if(!pl.wasCut){ continue; } auto& v=pl.vertices; auto& uvs=pl.uvs; auto node = DrawNodeWithTex::create(); node->SetTexture(pl.texId); //重心の計算(疑似) Vec2 center=Vec2(0,0); for(auto& vert : v){ center+=vert; } center = center/v.size(); for(auto& vert : v){ vert-=center; } auto grave=PhysicsBody::createPolygon(&v[0],v.size(),_pm); node->drawPolygonT(&v[0],&uvs[0],v.size(),cocos2d::Color4F::YELLOW,0,Color4F::WHITE); for(Vec2& uv : uvs){ log("u=%f,v=%f",uv.x,uv.y); } pl.position+=center; node->setPosition(pl.position); node->setPhysicsBody(grave); node->setTag(_tag++); pl.tag=node->getTag(); pl.wasCut=false; addChild(node); DrawNode* border=DrawNode::create(); border->drawPolygon(&v[0],v.size(),Color4F(0,0,0,0.0),BORDER_WIDTH,Color4F::WHITE); node->addChild(border); } --_slushLimit; }
void Pipe::SpawnPipe( cocos2d::Layer *layer ) { CCLOG( "SPAWN PIPE" ); auto topPipe = Sprite::create( "res/Pipe.png" ); auto bottomPipe = Sprite::create( "res/Pipe.png" ); auto topPipeBody = PhysicsBody::createBox( topPipe->getContentSize( ) ); auto bottomPipeBody = PhysicsBody::createBox( bottomPipe->getContentSize( ) ); auto random = CCRANDOM_0_1( ); if ( random < LOWER_SCREEN_PIPE_THRESHOLD ) { random = LOWER_SCREEN_PIPE_THRESHOLD; } else if ( random > UPPER_SCREEN_PIPE_THRESHOLD ) { random = UPPER_SCREEN_PIPE_THRESHOLD; } auto topPipePosition = ( random * visibleSize.height ) + ( topPipe->getContentSize( ).height / 2 ); topPipeBody->setDynamic( false ); bottomPipeBody->setDynamic( false ); topPipeBody->setCollisionBitmask( OBSTACLE_COLLISION_BITMASK ); bottomPipeBody->setCollisionBitmask( OBSTACLE_COLLISION_BITMASK ); topPipeBody->setContactTestBitmask( true ); bottomPipeBody->setContactTestBitmask( true ); topPipe->setPhysicsBody( topPipeBody ); bottomPipe->setPhysicsBody( bottomPipeBody ); topPipe->setPosition( Point( visibleSize.width + topPipe->getContentSize( ).width + origin.x, topPipePosition ) ); bottomPipe->setPosition( Point( topPipe->getPositionX(), topPipePosition - ( Sprite::create( "res/Ball.png" )->getContentSize( ).height * PIPE_GAP ) - topPipe->getContentSize().height ) ); layer->addChild( topPipe ); layer->addChild( bottomPipe ); auto topPipeAction = MoveBy::create( PIPE_MOVEMENT_SPEED * visibleSize.width, Point( -visibleSize.width * 1.5, 0 ) ); auto bottomPipeAction = MoveBy::create( PIPE_MOVEMENT_SPEED * visibleSize.width, Point( -visibleSize.width * 1.5, 0 ) ); topPipe->runAction( topPipeAction ); bottomPipe->runAction( bottomPipeAction ); auto pointNode = Node::create( ); auto pointBody = PhysicsBody::createBox( Size( 1, Sprite::create( "res/Ball.png" )->getContentSize( ).height * PIPE_GAP ) ); pointBody->setDynamic( false ); pointBody->setCollisionBitmask( POINT_COLLISION_BITMASK ); pointBody->setContactTestBitmask( true ); pointNode->setPhysicsBody( pointBody ); pointNode->setPosition( Point( topPipe->getPositionX( ), topPipe->getPositionY( ) - ( topPipe->getContentSize( ).height / 2 ) - ( ( Sprite::create( "res/Ball.png" )->getContentSize( ).height * PIPE_GAP ) / 2 ) ) ); layer->addChild( pointNode ); auto pointNodeAction = MoveBy::create( PIPE_MOVEMENT_SPEED * visibleSize.width, Point( -visibleSize.width * 1.5, 0 ) ); pointNode->runAction( pointNodeAction ); }
bool LevelFifteen::init() { if (!Layer::init()) { return false; } // 用于解决刚体穿透问题 this->scheduleUpdate(); // 计时器 this->schedule(schedule_selector(LevelFifteen::timeCounter), 1.0f); auto visibleSize = Director::getInstance()->getVisibleSize(); auto origin = Director::getInstance()->getVisibleOrigin(); // 加载背景贴图 auto spriteBg = Sprite::create("background.png"); spriteBg->setAnchorPoint(Vec2::ZERO); spriteBg->setPosition(Vec2::ZERO); addChild(spriteBg); // 将资源加载到精灵帧缓存 SpriteFrameCache::getInstance()->addSpriteFramesWithFile("threeColor.plist"); ballOne = Sprite::createWithSpriteFrameName("hero.png"); ballOne->setPosition(visibleSize.width / 2.0f, visibleSize.height / 2.0f); auto ballBodyOne = PhysicsBody::createCircle(ballOne->getContentSize().width / 2, PHYSICSBODY_MATERIAL_DEFAULT); //是否设置物理为静态 //ballBodyOne->setDynamic(false); //设置物理的恢复力 ballBodyOne->getShape(0)->setRestitution(0.5f); //设置物体的摩擦力 ballBodyOne->getShape(0)->setFriction(0.0f); ballBodyOne->getShape(0)->setDensity(0.3f); // 设置质量 质量等于密度乘以面积 //ballBodyOne->getShape(0)->setMass(5000); // 设置物体是否受重力系数影响 ballBodyOne->setGravityEnable(true); ballBodyOne->setCategoryBitmask(1);// 分类掩码 ballBodyOne->setCollisionBitmask(1 | 2 | 4 | 8);// 碰撞掩码 ballBodyOne->setContactTestBitmask(2);// 接触测试掩码 // 把物体添加到精灵 ballOne->setPhysicsBody(ballBodyOne); this->addChild(ballOne); // 创建抢食者(黑色) Sprite* black = nullptr; PhysicsBody* blackBody = nullptr; Vec2 arrBlack[] = { Vec2(-34.00000, -32.50000), Vec2(-15.00000, 36.00000), Vec2(35.00000, -15.00000) }; int indexBlack = CCRANDOM_0_1() * 3; switch (indexBlack) { case 0: { black = Sprite::createWithSpriteFrameName("black1.png"); blackBody = PhysicsBody::createBox(black->getContentSize(), PHYSICSBODY_MATERIAL_DEFAULT); } break; case 1: { black = Sprite::createWithSpriteFrameName("black2.png"); blackBody = PhysicsBody::createCircle(black->getContentSize().width / 2.0f, PHYSICSBODY_MATERIAL_DEFAULT); } break; case 2: { black = Sprite::createWithSpriteFrameName("black3.png"); blackBody = PhysicsBody::createPolygon(arrBlack, 3, PHYSICSBODY_MATERIAL_DEFAULT); } break; default: break; } black->setPosition(visibleSize.width / 2.0f, visibleSize.height / 2.0f); blackBody->setDynamic(true); blackBody->setGravityEnable(false); blackBody->setCategoryBitmask(8); blackBody->setCollisionBitmask(1 | 2 | 4 | 8); blackBody->setContactTestBitmask(2); black->setPhysicsBody(blackBody); this->addChild(black); //创建一个盒子,用来碰撞 auto edgeSpace = Sprite::create(); auto boundBody = PhysicsBody::createEdgeBox(visibleSize, PHYSICSBODY_MATERIAL_DEFAULT, 3); boundBody->getShape(0)->setFriction(0.0f); boundBody->getShape(0)->setRestitution(1.0f); edgeSpace->setPhysicsBody(boundBody); edgeSpace->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2)); this->addChild(edgeSpace); edgeSpace->setTag(0); boundBody->setCategoryBitmask(4); boundBody->setCollisionBitmask(1 | 2 | 4 | 8); boundBody->setContactTestBitmask(0); // 创建yuan auto white1 = Sprite::createWithSpriteFrameName("white2.png"); auto whiteBody1 = PhysicsBody::createCircle(white1->getContentSize().width / 2.0f, PHYSICSBODY_MATERIAL_DEFAULT); whiteBody1->setDynamic(false); whiteBody1->setCategoryBitmask(4); whiteBody1->setCollisionBitmask(1 | 2 | 4 | 8); whiteBody1->setContactTestBitmask(0); white1->setPhysicsBody(whiteBody1); this->addChild(white1); // 正方形 auto white1_2 = Sprite::createWithSpriteFrameName("white1.png"); auto whiteBody1_2 = PhysicsBody::createBox(white1_2->getContentSize(), PHYSICSBODY_MATERIAL_DEFAULT); whiteBody1_2->setDynamic(false); whiteBody1_2->setCategoryBitmask(4); whiteBody1_2->setCollisionBitmask(1 | 2 | 4 | 8); whiteBody1_2->setContactTestBitmask(0); white1_2->setPhysicsBody(whiteBody1_2); this->addChild(white1_2); // 创建三角形 Vec2 arr[] = { Vec2(-16.50000, 36.00000), Vec2(35.50000, -15.00000), Vec2(-34.00000, -32.50000) }; auto white3 = Sprite::createWithSpriteFrameName("white3.png"); auto whiteBody3 = PhysicsBody::createPolygon(arr, 3, PHYSICSBODY_MATERIAL_DEFAULT); whiteBody3->setDynamic(false); whiteBody3->setCategoryBitmask(4); whiteBody3->setCollisionBitmask(1 | 2 | 4 | 8); whiteBody3->setContactTestBitmask(0); white3->setPhysicsBody(whiteBody3); this->addChild(white3); // 随机位置 int index = CCRANDOM_0_1() * 3; switch (index) { case 0: { white1->setPosition(visibleSize.width / 2.0f, visibleSize.height / 2.0f + 200.0f); white1_2->setPosition(visibleSize.width / 2.0f + 200.0f, visibleSize.height / 2.0f); white3->setPosition(visibleSize.width / 2.0f - 200.0f, visibleSize.height / 2.0f); } break; case 1: { white1_2->setPosition(visibleSize.width / 2.0f, visibleSize.height / 2.0f + 200.0f); white1->setPosition(visibleSize.width / 2.0f + 200.0f, visibleSize.height / 2.0f); white3->setPosition(visibleSize.width / 2.0f - 200.0f, visibleSize.height / 2.0f); } break; case 2: { white3->setPosition(visibleSize.width / 2.0f, visibleSize.height / 2.0f + 200.0f); white1->setPosition(visibleSize.width / 2.0f + 200.0f, visibleSize.height / 2.0f); white1_2->setPosition(visibleSize.width / 2.0f - 200.0f, visibleSize.height / 2.0f); } break; default: break; } // 正方形旋转 auto rotation = RotateBy::create(1, 360); auto rotationback = rotation->reverse(); auto seq = Sequence::create(rotation, rotationback, nullptr); auto repeat = RepeatForever::create(seq); white1->runAction(repeat); // // 第二个正方形旋转 auto rotation_1 = RotateBy::create(2, 360); auto rotationback_1 = rotation_1->reverse(); auto seq1 = Sequence::create(rotation_1, rotationback_1, nullptr); auto repeat1 = RepeatForever::create(seq1); white1_2->runAction(repeat1); // 三角形旋转 auto rotation_2 = RotateBy::create(2, 360); auto rotationback_2 = rotation_2->reverse(); auto seq2 = Sequence::create(rotation_2, rotationback_2, nullptr); auto repeat2 = RepeatForever::create(seq2); white3->runAction(repeat2); auto yuantong0 = Sprite::createWithSpriteFrameName("yuantong.png"); yuantong0->setPosition(Vec2(visibleSize.width / 2.0f, visibleSize.height + yuantong0->getContentSize().height / 2.0f)); auto yuantongBody = PhysicsBody::createBox(yuantong0->getContentSize(), PHYSICSBODY_MATERIAL_DEFAULT); yuantongBody->setDynamic(false); yuantongBody->setCategoryBitmask(4); yuantongBody->setCollisionBitmask(1 | 2 | 4 | 8); yuantongBody->setContactTestBitmask(0); yuantong0->setPhysicsBody(yuantongBody); this->addChild(yuantong0); auto moveby0 = MoveBy::create(1.0f, Vec2(0, -90)); auto moveby0back = moveby0->reverse(); auto easein = EaseBackIn::create(moveby0); auto seq0 = Sequence::create(easein, CallFuncN::create(CC_CALLBACK_1(LevelFifteen::callbackC, this)), moveby0back, nullptr); auto repeat0 = RepeatForever::create(seq0); yuantong0->runAction(repeat0); listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = [=](Touch* touch, Event* event){ auto touchPosition = touch->getLocation(); Vec2 force = Vec2::ZERO; if ((touchPosition.x > visibleSize.width / 2.0f) && (touchPosition.y < visibleSize.height / 2.0f)) { force = Vec2(50000.0f, 0.0f); } else if ((touchPosition.y < visibleSize.height / 2.0f) && (touchPosition.x < visibleSize.width / 2.0f)) { force = Vec2(-50000.0f, 0.0f); } else { force = Vec2(0.0f, 50000.0f); } ballOne->getPhysicsBody()->applyImpulse(force); return true; }; _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); // 时间显示文本 test = LabelAtlas::create(StringUtils::toString(nGoal), "1.png", 14, 21, '0'); test->setScale(2.0f); test->setAnchorPoint(Vec2::ANCHOR_MIDDLE); test->setPosition(Vec2(test->getContentSize().width + 10, visibleSize.height - test->getContentSize().height)); this->addChild(test); test2 = LabelAtlas::create(StringUtils::toString(newTimes), "1.png", 14, 21, '0'); test2->setScale(2.0f); test2->setAnchorPoint(Vec2::ANCHOR_MIDDLE); test2->setPosition(Vec2(visibleSize.width - test2->getContentSize().width - 10, visibleSize.height - test2->getContentSize().height)); this->addChild(test2); test3 = LabelAtlas::create(StringUtils::toString(nTimes), "1.png", 14, 21, '0'); test3->setScale(2.0f); test3->setAnchorPoint(Vec2::ANCHOR_MIDDLE); test3->setPosition(Vec2(test3->getContentSize().width*4.0f + 40, visibleSize.height - test3->getContentSize().height)); this->addChild(test3); return true; }
bool LevelTwentytwo::init() { if (!Layer::init()) { return false; } // 用于解决刚体穿透问题 this->scheduleUpdate(); // 计时器 this->schedule(schedule_selector(LevelTwentytwo::timeCounter), 1.0f); auto visibleSize = Director::getInstance()->getVisibleSize(); auto origin = Director::getInstance()->getVisibleOrigin(); // 加载背景贴图 auto spriteBg = Sprite::create("background.png"); spriteBg->setAnchorPoint(Vec2::ZERO); spriteBg->setPosition(Vec2::ZERO); addChild(spriteBg); ballOne = Sprite::createWithSpriteFrameName("hero.png"); ballOne->setPosition(visibleSize.width / 2.0f, ballOne->getContentSize().height); auto ballBodyOne = PhysicsBody::createCircle(ballOne->getContentSize().width / 2, PHYSICSBODY_MATERIAL_DEFAULT); //是否设置物理为静态 //ballBodyOne->setDynamic(false); //设置物理的恢复力 ballBodyOne->getShape(0)->setRestitution(0.5f); //设置物体的摩擦力 ballBodyOne->getShape(0)->setFriction(0.0f); ballBodyOne->getShape(0)->setDensity(0.3f); // 设置质量 质量等于密度乘以面积 //ballBodyOne->getShape(0)->setMass(5000); // 设置物体是否受重力系数影响 ballBodyOne->setGravityEnable(true); ballBodyOne->setCategoryBitmask(1);// 分类掩码 ballBodyOne->setCollisionBitmask(1 | 2 | 4 | 8);// 碰撞掩码 ballBodyOne->setContactTestBitmask(8);// 接触测试掩码 // 把物体添加到精灵 ballOne->setPhysicsBody(ballBodyOne); this->addChild(ballOne); auto girl = Sprite::createWithSpriteFrameName("girl.png"); girl->setPosition(visibleSize.width / 2.0f, visibleSize.height / 2.0f + 250.0f); auto girlBody = PhysicsBody::createCircle(girl->getContentSize().width / 2.0f, PHYSICSBODY_MATERIAL_DEFAULT); girlBody->setDynamic(false); girlBody->setGravityEnable(false); girlBody->setCategoryBitmask(8); girlBody->setCollisionBitmask(1); girlBody->setContactTestBitmask(1); girl->setPhysicsBody(girlBody); this->addChild(girl); //创建一个盒子,用来碰撞 auto edgeSpace = Sprite::create(); auto boundBody = PhysicsBody::createEdgeBox(visibleSize, PHYSICSBODY_MATERIAL_DEFAULT, 3); boundBody->getShape(0)->setFriction(0.0f); boundBody->getShape(0)->setRestitution(1.0f); edgeSpace->setPhysicsBody(boundBody); edgeSpace->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2)); this->addChild(edgeSpace); edgeSpace->setTag(0); boundBody->setCategoryBitmask(4); boundBody->setCollisionBitmask(1 | 2 | 4); boundBody->setContactTestBitmask(0); // 随机位置 int index = CCRANDOM_0_1() * 4; auto suiji1 = 0; auto suiji2 = 0; auto suiji3 = 0; switch (index) { case 0: suiji1 = CCRANDOM_0_1() * 240; suiji2 = -CCRANDOM_0_1() * 100; suiji3 = -CCRANDOM_0_1() * 150; break; case 1: suiji1 = -CCRANDOM_0_1() * 240; suiji2 = -CCRANDOM_0_1() * 100; suiji3 = -CCRANDOM_0_1() * 150; break; case 2: suiji1 = -CCRANDOM_0_1() * 240; suiji2 = CCRANDOM_0_1() * 100; suiji3 = CCRANDOM_0_1() * 150; break; case 3: suiji1 = CCRANDOM_0_1() * 240; suiji2 = CCRANDOM_0_1() * 100; suiji3 = CCRANDOM_0_1() * 150; break; default: break; } // 创建yuan auto white1 = Sprite::createWithSpriteFrameName("white2.png"); white1->setPosition(visibleSize.width / 2.0f + 200.0f, visibleSize.height / 2.0f - 150.0f); auto whiteBody1 = PhysicsBody::createCircle(white1->getContentSize().width / 2.0f, PHYSICSBODY_MATERIAL_DEFAULT); whiteBody1->setDynamic(false); whiteBody1->setCategoryBitmask(4); whiteBody1->setCollisionBitmask(1 | 2 | 4); whiteBody1->setContactTestBitmask(0); white1->setPhysicsBody(whiteBody1); this->addChild(white1); // 正方形 auto white1_2 = Sprite::createWithSpriteFrameName("white1.png"); white1_2->setPosition(visibleSize.width / 2.0f - 200.0f, visibleSize.height / 2.0f + 150.0f); auto whiteBody1_2 = PhysicsBody::createBox(white1_2->getContentSize(), PHYSICSBODY_MATERIAL_DEFAULT); whiteBody1_2->setDynamic(false); whiteBody1_2->setCategoryBitmask(4); whiteBody1_2->setCollisionBitmask(1 | 2 | 4); whiteBody1_2->setContactTestBitmask(0); white1_2->setPhysicsBody(whiteBody1_2); this->addChild(white1_2); // 创建三角形 Vec2 arr[] = { Vec2(-16.50000, 36.00000), Vec2(35.50000, -15.00000), Vec2(-34.00000, -32.50000) }; auto white3 = Sprite::createWithSpriteFrameName("white3.png"); white3->setPosition(visibleSize.width / 2.0f + suiji3, visibleSize.height / 2.0f + suiji2); auto whiteBody3 = PhysicsBody::createPolygon(arr, 3, PHYSICSBODY_MATERIAL_DEFAULT); whiteBody3->setDynamic(false); whiteBody3->setCategoryBitmask(4); whiteBody3->setCollisionBitmask(1 | 2 | 4); whiteBody3->setContactTestBitmask(0); white3->setPhysicsBody(whiteBody3); this->addChild(white3); auto rotation_1 = RotateBy::create(2, 360); auto rotationback_1 = rotation_1->reverse(); auto seq1 = Sequence::create(rotation_1, rotationback_1, nullptr); auto repeat1 = RepeatForever::create(seq1); white1_2->runAction(repeat1); auto yuantong0 = Sprite::createWithSpriteFrameName("yuantong.png"); yuantong0->setPosition(Vec2(visibleSize.width / 2.0f, visibleSize.height + yuantong0->getContentSize().height / 2.0f)); auto yuantongBody = PhysicsBody::createBox(yuantong0->getContentSize(), PHYSICSBODY_MATERIAL_DEFAULT); yuantongBody->setDynamic(false); yuantongBody->setCategoryBitmask(4); yuantongBody->setCollisionBitmask(1 | 2 | 4); yuantongBody->setContactTestBitmask(0); yuantong0->setPhysicsBody(yuantongBody); this->addChild(yuantong0); auto yuantong1 = Sprite::createWithSpriteFrameName("yuantong.png"); yuantong1->setPosition(Vec2(visibleSize.width / 2.0f - yuantong1->getContentSize().width / 2 * 3, visibleSize.height + yuantong1->getContentSize().height / 2.0f)); auto yuantongBody1 = PhysicsBody::createBox(yuantong1->getContentSize(), PHYSICSBODY_MATERIAL_DEFAULT); yuantongBody1->setDynamic(false); yuantongBody1->setCategoryBitmask(4); yuantongBody1->setCollisionBitmask(1 | 2 | 4); yuantongBody1->setContactTestBitmask(0); yuantong1->setPhysicsBody(yuantongBody1); this->addChild(yuantong1); auto moveby0 = MoveBy::create(0.5f, Vec2(0, -90)); auto moveby0back = moveby0->reverse(); auto easein = EaseBackIn::create(moveby0); auto seq0 = Sequence::create(easein, CallFuncN::create(CC_CALLBACK_1(LevelTwentytwo::callbackC, this)), moveby0back, nullptr); auto repeat0 = RepeatForever::create(seq0); yuantong0->runAction(repeat0); auto moveby1 = MoveBy::create(1.0f, Vec2(0, -90)); auto moveby1back = moveby1->reverse(); auto easein1 = EaseBackIn::create(moveby1); auto yuantongseq1 = Sequence::create(easein1, CallFuncN::create(CC_CALLBACK_1(LevelTwentytwo::callbackC, this)), moveby1back, nullptr); auto yuantongrepeat1 = RepeatForever::create(yuantongseq1); yuantong1->runAction(yuantongrepeat1); listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = [=](Touch* touch, Event* event){ Vec2 force = Vec2::ZERO; force = Vec2(0, 50000.0f); ballOne->getPhysicsBody()->applyImpulse(force); return true; }; _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); // 时间显示文本 test = LabelAtlas::create(StringUtils::toString(nTimes), "1.png", 14, 21, '0'); test->setScale(2.0f); test->setAnchorPoint(Vec2::ANCHOR_MIDDLE); test->setPosition(Vec2(test->getContentSize().width + 10, visibleSize.height - test->getContentSize().height)); this->addChild(test); test2 = LabelAtlas::create(StringUtils::toString(newTimes), "1.png", 14, 21, '0'); test2->setScale(2.0f); test2->setAnchorPoint(Vec2::ANCHOR_MIDDLE); test2->setPosition(Vec2(visibleSize.width - test2->getContentSize().width - 10, visibleSize.height - test2->getContentSize().height)); this->addChild(test2); return true; }
void Pipe::SpawnPipe1( cocos2d::Layer *layer ) { CCLOG( "SPAWN PIPE" ); auto topPipe = Sprite::create( "Pipe.png" ); auto bottomPipe = Sprite::create( "Pipe.png" ); auto topPipeBody = PhysicsBody::createBox( topPipe->getContentSize( ) ); auto bottomPipeBody = PhysicsBody::createBox( bottomPipe->getContentSize( ) ); /* auto random = CCRANDOM_0_1( ); if ( random < LOWER_SCREEN_PIPE_THRESHOLD ) { random = LOWER_SCREEN_PIPE_THRESHOLD; } else if ( random > UPPER_SCREEN_PIPE_THRESHOLD ) { random = UPPER_SCREEN_PIPE_THRESHOLD; } auto topPipePosition = ( random * visibleSize.height ) + ( topPipe->getContentSize().height / 2 ); */ topPipeBody->setDynamic( false ); bottomPipeBody->setDynamic( false ); topPipe->setPhysicsBody( topPipeBody ); bottomPipe->setPhysicsBody( bottomPipeBody ); //collision handle topPipeBody->setCollisionBitmask(OBSTACLE_COLLISION_BITMASK); topPipeBody->setContactTestBitmask(true); bottomPipeBody->setCollisionBitmask(OBSTACLE_COLLISION_BITMASK); bottomPipeBody->setContactTestBitmask(true); //topPipe->setPosition( Point( visibleSize.width + topPipe->getContentSize().width + origin.x // ,topPipePosition ) ); //bottomPipe->setPosition( Point( topPipe->getPositionX(), topPipePosition - ( Sprite::create( "Ball.png" )->getContentSize( ).height * PIPE_GAP ) - topPipe->getContentSize().height ) ); // new pipes position //setting the random number between min and max auto minY = origin.y + Sprite::create( "Ball.png" )->getContentSize( ).height/4 - (topPipe->getContentSize().height/2); auto maxY = origin.y - Sprite::create( "Ball.png" )->getContentSize( ).height/4 - Sprite::create( "Ball.png" )->getContentSize( ).height - Sprite::create( "Ball.png" )->getContentSize( ).height/3 + visibleSize.height - topPipe->getContentSize().height/2; //float randNum = rand()% (float)(maxY-minY + 1.0) + minY; float randNum = minY + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(maxY-minY))); //setting position bottomPipe->setPosition(Point(visibleSize.width + topPipe->getContentSize().width + origin.x ,randNum)); topPipe->setPosition(Point(bottomPipe->getPositionX() ,bottomPipe->getPositionY() + Sprite::create( "Ball.png" )->getContentSize( ).height + (Sprite::create( "Ball.png" )->getContentSize( ).height/3) + (topPipe->getContentSize().height))); // end new pipe possition layer->addChild( topPipe ); layer->addChild( bottomPipe ); auto topPipeAction = MoveBy::create (PIPE_MOVEMENT_SPEED * visibleSize.width, Point(-visibleSize.width * 1.5 , 0)); auto bottomPipeAction = MoveBy::create (PIPE_MOVEMENT_SPEED * visibleSize.width, Point(-visibleSize.width * 1.5 , 0)); topPipe->runAction(topPipeAction); bottomPipe->runAction(bottomPipeAction); }
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } i = 0; j = 0; Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); EventListenerPhysicsContact *contact_listener = EventListenerPhysicsContact::create(); contact_listener->onContactBegin = CC_CALLBACK_1(HelloWorld::onContactBegin, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(contact_listener, this); touch_listener = EventListenerTouchOneByOne::create(); touch_listener->setSwallowTouches(false); touch_listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan, this); touch_listener->onTouchMoved = CC_CALLBACK_2(HelloWorld::onTouchMoved, this); touch_listener->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded, this); touch_listener->onTouchCancelled = CC_CALLBACK_2(HelloWorld::onTouchCancelled, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touch_listener, this); auto body = PhysicsBody::createEdgeBox(visibleSize); auto edgeNode = Node::create(); edgeNode->setPosition(visibleSize.width/2,visibleSize.height/2); edgeNode->setPhysicsBody(body); this->addChild(edgeNode); ///////////////////////////// // 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... LayerColor* _layer = LayerColor::create(Color4B(255, 255, 255, 255), visibleSize.width,visibleSize.height); this->addChild(_layer); _player = Sprite::create("player-hd.png"); _player->setPosition(visibleSize.width/8,visibleSize.height/2); this->addChild(_player); // add a label shows "Hello World" // create and initialize a label this->schedule(schedule_selector(HelloWorld::addMonster),1); //this->schedule(schedule_selector(HelloWorld::GameUpdate)); return true; }