Exemplo n.º 1
0
Camera* HMDScene::setupCamera(float ratio, bool left) {
  
  auto s = Director::getInstance()->getWinSize();
  auto sizeInpixels = Director::getInstance()->getWinSizeInPixels();
  
  auto fboSize = Size(sizeInpixels.width * 1.f, sizeInpixels.height * 1.f);
  auto fbo = experimental::FrameBuffer::create(1, fboSize.width, fboSize.height);
  auto rt = experimental::RenderTarget::create(fboSize.width, fboSize.height);
  auto rtDS = experimental::RenderTargetDepthStencil::create(fboSize.width, fboSize.height);
  
  fbo->attachRenderTarget(rt);
  fbo->attachDepthStencilTarget(rtDS);
  
  auto sprite = Sprite::createWithTexture(fbo->getRenderTarget()->getTexture());
  sprite->setPosition((left ? s.width * 0.25f : s.width * 0.75f) , s.height * 0.5f);
  sprite->setRotation3D(Vec3(0.0f, 180.0f, 180.0f));
  sprite->setScale(0.5f, 1.0f);
  
  Scene::addChild(sprite);
  
  auto cam = Camera::createPerspective(60, ratio, 0.01f, 100.0f);
  cam->setPosition3D(Vec3(0.0f, 0.0f, 0.0f));
  cam->setCameraFlag(left ? CameraFlag::USER7 : CameraFlag::USER8);
  cam->setDepth(-1);
  cam->setName( (left ? "HMD-Cam-L" : "HMD-Cam-R") );
  cam->setFrameBufferObject(fbo);
  // useful for debugging viewport stuff
  //fbo->setClearColor(Color4F( (left ? 0.25f : 0.0f) , (left ? 0.0f : 0.25f), 0, 1));
  
  return cam;
}
Exemplo n.º 2
0
bool CreditsScene::init()
{
    assert(TRBaseScene::init());



    auto layer = Layer::create();
    this->addChild(layer);

    auto size = Director::getInstance()->getVisibleSize();

    auto camera = Camera::createPerspective(60, size.width/size.height, 0.1, 1000000);
    camera->setCameraFlag(CameraFlag::USER1);
    layer->addChild(camera);
    camera->setCameraMask((unsigned short)CameraFlag::USER1);
    camera->setPosition3D({0,0,50});
    camera->lookAt({0,0,0}, {0,1,0});
    _mainLayer = layer;
    _mainCamera = camera;


    auto hub = Node::create();
    hub->setPosition3D({0,0,0});
    hub->setCameraMask(_mainCamera->getCameraMask());
    _mainLayer->addChild(hub);
    _hub = hub;

    initCreditsThings();
    initTouchThings();


    return true;
}
Exemplo n.º 3
0
Sprite3DUVAnimationTest::Sprite3DUVAnimationTest()
{
    //the offset use to translating texture
    _cylinder_texture_offset = 0;
    _shining_duraion = 0;
    Size visibleSize = Director::getInstance()->getVisibleSize();

    //use custom camera
    auto camera = Camera::createPerspective(60,visibleSize.width/visibleSize.height,0.1,200);
    camera->setCameraFlag(CameraFlag::USER1);

    //create cylinder
    auto cylinder = Sprite3D::create("Sprite3DTest/cylinder.c3b");

    //create and set our custom shader
    auto shader =GLProgram::createWithFilenames("Sprite3DTest/cylinder.vert","Sprite3DTest/cylinder.frag");
    _state = GLProgramState::create(shader);
    cylinder->setGLProgramState(_state);

    _state->setUniformFloat("offset",_cylinder_texture_offset);
    _state->setUniformFloat("duration",_shining_duraion);
    //pass mesh's attribute to shader
    long offset = 0;
    auto attributeCount = cylinder->getMesh()->getMeshVertexAttribCount();
    for (auto i = 0; i < attributeCount; i++) {
        auto meshattribute = cylinder->getMesh()->getMeshVertexAttribute(i);
        _state->setVertexAttribPointer(s_attributeNames[meshattribute.vertexAttrib],
            meshattribute.size,
            meshattribute.type,
            GL_FALSE,
            cylinder->getMesh()->getVertexSizeInBytes(),
            (GLvoid*)offset);
        offset += meshattribute.attribSizeBytes;
    }

    //create the second texture for cylinder
    auto shining_texture = Director::getInstance()->getTextureCache()->addImage("Sprite3DTest/caustics.png");
    Texture2D::TexParams tRepeatParams;//set texture parameters
    tRepeatParams.magFilter = GL_NEAREST;
    tRepeatParams.minFilter = GL_NEAREST;
    tRepeatParams.wrapS = GL_REPEAT;
    tRepeatParams.wrapT = GL_REPEAT;
    shining_texture->setTexParameters(tRepeatParams); 
    //pass the texture sampler to our custom shader
    _state->setUniformTexture("caustics",shining_texture);


    this->addChild(cylinder);
    this->setCameraMask(2); 
    this->addChild(camera);

    //adjust cylinder's position & rotation
    cylinder->setPosition3D(Vec3(0,-15,-50));
    cylinder->setRotation3D(Vec3(-90,0,0));

    //the callback function update cylinder's texcoord
    schedule(schedule_selector(Sprite3DUVAnimationTest::cylinderUpdate));
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

    //the offset use to translating texture
    this->cylinder_texture_offset = 0;
    this->shining_duraion = 0;
    Size visibleSize = Director::getInstance()->getVisibleSize();

    //use custom camera
    auto camera = Camera::createPerspective(60,visibleSize.width/visibleSize.height,0.1,200);
    camera->setCameraFlag(CameraFlag::USER1);
 
    auto cylinder = Sprite3D::create("cylinder.c3b");
    auto shader =GLProgram::createWithFilenames("cylinder.vert","cylinder.frag");
    
    state = GLProgramState::create(shader);

    cylinder->setGLProgramState(state);
    
    //set attrib to shader
    long offset = 0;
    auto attributeCount = cylinder->getMesh()->getMeshVertexAttribCount();
    for (auto k = 0; k < attributeCount; k++) {
        auto meshattribute = cylinder->getMesh()->getMeshVertexAttribute(k);
        state->setVertexAttribPointer(s_attributeNames[meshattribute.vertexAttrib],
            meshattribute.size,
            meshattribute.type,
            GL_FALSE,
            cylinder->getMesh()->getVertexSizeInBytes(),
            (GLvoid*)offset);
        offset += meshattribute.attribSizeBytes;
    }
    
    auto shining_texture = Director::getInstance()->getTextureCache()->addImage("caustics.png");
    Texture2D::TexParams tRepeatParams;
    tRepeatParams.magFilter = GL_LINEAR_MIPMAP_LINEAR;
    tRepeatParams.minFilter = GL_LINEAR;
    tRepeatParams.wrapS = GL_REPEAT;
    tRepeatParams.wrapT = GL_REPEAT;
    shining_texture->setTexParameters(tRepeatParams);
    state->setUniformTexture("caustics",shining_texture);
    cylinder->setPosition3D(Vec3(0,-15,-50));
    cylinder->setRotation3D(Vec3(-90,0,0));
    this->addChild(cylinder);
    this->setCameraMask(2);
    this->addChild(camera);

    schedule(schedule_selector(HelloWorld::cylinderUpdate));
    return true;
}
Exemplo n.º 5
0
bool GlassDemoScene::init()
{
    assert(TRBaseScene::init());
    _layer = Layer::create();

    this->addChild(_layer);

    auto size = Director::getInstance()->getVisibleSize();

    auto _formCamera = Camera::createPerspective(60, size.width/size.height, 0.01, 1000);
    _formCamera->setPosition3D({0,0,0});
    _formCamera->lookAt(Vec3{0,0,-20},Vec3{0,1,0});
    _formCamera->setCameraFlag(CameraFlag::USER1);
    _layer->addChild(_formCamera);
    _formCamera->setCameraMask((unsigned short)CameraFlag::USER1);
    _camera = _formCamera;

    _glass = DynamicGlass::create(1.2,1.2,10,10);
    _glass->setCameraMask(_camera->getCameraMask());
    _layer->addChild(_glass);
    _glass->setPosition3D({0,0,0});





    this->addCommonBtn({0.1f,0.95f}, "back", [](){
        Director::getInstance()->popScene();
    });
    this->addCommonBtn({0.1f,0.9f}, "hit", [this](){
        _glass->hit(1.0);
    });

    this->addCommonBtn({0.1f,0.85f}, "reset", [this](){
        _glass->reset();
    });

    ///acce
    _acceEffect = AcceEffectSpace::create();
    _acceEffect->setCameraMask(_camera->getCameraMask());
    _acceEffect->setPosition3D({0,0,0});
    _layer->addChild(_acceEffect);

    this->addCommonBtn({0.9f, 0.8f}, "per +", [this](){_percent += 0.1;});
    this->addCommonBtn({0.9f, 0.75f}, "per -", [this](){_percent -= 0.1;});

    scheduleUpdate();

    return  true;
}
Exemplo n.º 6
0
void CameraFrameBufferTest::onEnter()
{
    auto sizeInpixels = Director::getInstance()->getWinSizeInPixels();
    auto size = Director::getInstance()->getWinSize();
    auto fboSize = Size(sizeInpixels.width * 1, sizeInpixels.height * 1.5);
    auto fbo = experimental::FrameBuffer::create(1, fboSize.width, fboSize.height);
    
    CameraBaseTest::onEnter();
    //auto sprite = Sprite::createWithTexture(fbo);
    //sprite->setPosition(Vec2(100,100));
    //std::string filename = "Sprite3DTest/girl.c3b";
    //auto sprite = Sprite3D::create(filename);
    //sprite->setScale(1.0);
    //auto animation = Animation3D::create(filename);
    //if (animation)
    //{
    //    auto animate = Animate3D::create(animation);
        
    //    sprite->runAction(RepeatForever::create(animate));
    //}
    //sprite->setPosition(Vec2(100,100));
    auto rt = experimental::RenderTarget::create(fboSize.width, fboSize.height);
    auto rtDS = experimental::RenderTargetDepthStencil::create(fboSize.width, fboSize.height);
    fbo->attachRenderTarget(rt);
    fbo->attachDepthStencilTarget(rtDS);
    auto sprite = Sprite::createWithTexture(fbo->getRenderTarget()->getTexture());
    sprite->setScale(0.3);
    sprite->runAction(RepeatForever::create(RotateBy::create(1, 90)));
    sprite->setPosition(size.width/2, size.height/2);
    addChild(sprite);
    
    auto sprite2 = Sprite::create(s_pathGrossini);
    sprite2->setPosition(Vec2(size.width/5,size.height/5));
    addChild(sprite2);
    sprite2->setCameraMask((unsigned short)CameraFlag::USER1);
    auto move = MoveBy::create(1.0, Vec2(100,100));
    sprite2->runAction(
                       RepeatForever::create(
                                             Sequence::createWithTwoActions(
                                                                            move, move->reverse())
                                             )
                       );
    
    auto camera = Camera::create();
    camera->setCameraFlag(CameraFlag::USER1);
    camera->setDepth(-1);
    camera->setFrameBufferObject(fbo);
    fbo->setClearColor(Color4F(1,1,1,1));
    addChild(camera);
}
Exemplo n.º 7
0
LightTest::LightTest()
    : _directionalLight(nullptr)
    , _pointLight(nullptr)
    , _spotLight(nullptr)
{
    addSprite();
    addLights();
    scheduleUpdate();

    auto s = Director::getInstance()->getWinSize();
    auto camera = Camera::createPerspective(60, (GLfloat)s.width/s.height, 1.0f, 1000.0f);
    camera->setCameraFlag(CameraFlag::USER1);
    camera->setPosition3D(Vec3(0.0, 100, 100));
    camera->lookAt(Vec3(0.0, 0.0, 0.0), Vec3(0.0, 1.0, 0.0));
    addChild(camera);

    TTFConfig ttfConfig("fonts/arial.ttf", 15);
    _ambientLightLabel = Label::createWithTTF(ttfConfig,"Ambient Light ON");
    _ambientLightLabel->retain();
    auto menuItem0 = MenuItemLabel::create(_ambientLightLabel, CC_CALLBACK_1(LightTest::SwitchLight,this,LightType::AMBIENT));
    _directionalLightLabel = Label::createWithTTF(ttfConfig,"Directional Light OFF");
    _directionalLightLabel->retain();
    auto menuItem1 = MenuItemLabel::create(_directionalLightLabel, CC_CALLBACK_1(LightTest::SwitchLight,this,LightType::DIRECTIONAL));
    _pointLightLabel = Label::createWithTTF(ttfConfig,"Point Light OFF");
    _pointLightLabel->retain();
    auto menuItem2 = MenuItemLabel::create(_pointLightLabel, CC_CALLBACK_1(LightTest::SwitchLight,this,LightType::POINT));
    _spotLightLabel = Label::createWithTTF(ttfConfig,"Spot Light OFF");
    _spotLightLabel->retain();
    auto menuItem3 = MenuItemLabel::create(_spotLightLabel, CC_CALLBACK_1(LightTest::SwitchLight,this,LightType::SPOT));
    auto menu = Menu::create(menuItem0, menuItem1, menuItem2, menuItem3, nullptr);
    menu->setPosition(Vec2::ZERO);
    menuItem0->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT);
    menuItem0->setPosition( Vec2(VisibleRect::left().x, VisibleRect::top().y-50) );
    menuItem1->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT);
    menuItem1->setPosition( Vec2(VisibleRect::left().x, VisibleRect::top().y-100) );
    menuItem2->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT);
    menuItem2->setPosition( Vec2(VisibleRect::left().x, VisibleRect::top().y -150));
    menuItem3->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT);
    menuItem3->setPosition( Vec2(VisibleRect::left().x, VisibleRect::top().y -200));
    addChild(menu);
}
Exemplo n.º 8
0
// on "init" you need to initialize your instance
bool Lession25::init()
{
    if ( !Layer::init() )
    {
        return false;
    }

	auto winSize = Director::getInstance()->getWinSize();
	FileUtils::getInstance()->addSearchPath(FileUtils::getInstance()->getSearchPaths().at(0) + "Lession25/");

	////µÃµ½ÆÁÄ»³ß´ç
	auto s = Director::getInstance()->getWinSize();
	//´´½¨3DÉãÏñ»ú
	auto _camera = cocos2d::Camera::createPerspective(60, (GLfloat)s.width / s.height, 1, 1000);
	//ÉèÖÃÉãÏñ»úÑÛ¾¦Î»ÖÃ
	_camera->setPosition3D(Vec3(0, 200, 200));
	//ÉèÖÃÉãÏñ»ú¹Û²ìµãλÖÃ
	_camera->lookAt(Vec3(0, 0, 0));
	_camera->setCameraFlag(CameraFlag::USER1);
	addChild(_camera);

	//´´½¨¾²Ì¬Ä£ÐÍ
	auto spriteStatic3D = Sprite3D::create("water.c3t");
	_sprite3D = spriteStatic3D;
	spriteStatic3D->setCameraMask(2);
	spriteStatic3D->setScale(2);
	spriteStatic3D->setPosition3D(Vec3(0, 0, 0));
	spriteStatic3D->setRotation3D(Vec3(-90, 0, 0));
	addChild(spriteStatic3D);

	GLProgramState* state = GLProgramState::create(GLProgram::createWithFilenames("Lession25.vert", "Lession25.frag"));
	state->applyUniforms();
	spriteStatic3D->setGLProgramState(state);

    return true;

}
Scene* Chapter9_8::createScene()
{
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();
    auto winSize = Director::getInstance()->getWinSize();
    
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // create a scene
    // 'scene' is an autorelease object
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    auto scene = Scene::create();
    
    // add title
    auto label = LabelTTF::create("BillBoard", "Arial", 24);
    label->setPosition(Vec2(origin.x+visibleSize.width/2, origin.y+visibleSize.height/2).x,
                       Vec2(origin.x+visibleSize.width/2, origin.y+visibleSize.height).y - 30);
    
    scene->addChild(label, -1);
    
    //add the menu item for back to main menu
    label = LabelTTF::create("MainMenu", "Arial", 24);
    auto menuItem = MenuItemLabel::create(label);
    menuItem->setCallback([&](cocos2d::Ref *sender) {
        Director::getInstance()->replaceScene(Chapter9::createScene());
    });
    auto menu = Menu::create(menuItem, nullptr);
    menu->setPosition( Vec2::ZERO );
    menuItem->setPosition( Vec2(origin.x+visibleSize.width - 80, origin.y + 25) );
    scene->addChild(menu, 1);
    
    
    auto layer3D=Layer::create();
    scene->addChild(layer3D,2);
    
    static std::vector<BillBoard*> _billboards;
    for (int i = -4; i < 4; ++i)
    {
        auto billboard = BillBoard::create("Blue_Front1.png");
        billboard->setScale(0.5f);
        billboard->setPosition3D(Vec3(i * 50, 0.0f, 0));
        billboard->setBlendFunc(cocos2d::BlendFunc::ALPHA_NON_PREMULTIPLIED);
        _billboards.push_back(billboard);
        layer3D->addChild(billboard);
    }
    
    for (int i = -4; i < 4; ++i)
    {
        auto billboard = BillBoard::create("Blue_Front1.png");
        billboard->setScale(0.5f);
        billboard->setPosition3D(Vec3(i * 50, 0.0f, -50));
        billboard->setBlendFunc(cocos2d::BlendFunc::ALPHA_NON_PREMULTIPLIED);
        _billboards.push_back(billboard);
        layer3D->addChild(billboard);
    }
    
    // add camera
    auto camera=Camera::createPerspective(60, (GLfloat)winSize.width/winSize.height, 1, 1000);
    camera->setCameraFlag(CameraFlag::USER1);// set camera flag
    camera->setPosition3D(Vec3(0, 150, 230));
    camera->lookAt(Vec3(0, 0, 0), Vec3(0,1,0));
    
    // create camera action
    auto action = MoveBy::create(3, Vec2(100, 0));
    auto actionrev = action->reverse();
    auto actionback = MoveBy::create(3, Vec2(-100, 0));
    auto actionbackrev = actionback->reverse();
    auto seq = Sequence::create( action, actionrev, actionback, actionbackrev, nullptr );
    
    // run camera action
    camera->runAction( RepeatForever::create(seq) );
    
    layer3D->addChild(camera);
    
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // set camera mask
    // when node's camera-mask & camer-flag result is true, the node is visible for this camera.
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    layer3D->setCameraMask(0x2);
    
    // add select menue
    auto label1 = LabelTTF::create("Point Oriented", "Arial", 24);
    auto item1 = MenuItemLabel::create(label1);
    item1->setCallback([&](cocos2d::Ref *sender) {
        for (auto& billboard : _billboards) {
            billboard->setMode(BillBoard::Mode::VIEW_POINT_ORIENTED);
        }
    });
    auto label2 = LabelTTF::create("Plane Oriented", "Arial", 24);
    auto item2 = MenuItemLabel::create(label2);
    item2->setCallback([&](cocos2d::Ref *sender) {
        for (auto& billboard : _billboards) {
            billboard->setMode(BillBoard::Mode::VIEW_PLANE_ORIENTED);
        }
    });
    auto itemSize = item1->getContentSize();
    item1->setPosition( Vec2(origin.x + 100, origin.y+visibleSize.height - itemSize.height * 2));
    item2->setPosition( Vec2(origin.x + 100, origin.y+visibleSize.height - itemSize.height * 3));
    
    auto menuSelect = CCMenu::create(item1, item2, NULL);
    menuSelect->setPosition(Vec2(0,0));
    scene->addChild(menuSelect, 1);
    
    // return the scene
    return scene;
}
Exemplo n.º 10
0
bool LoadingScene::init()
{
    assert(TRBaseScene::init());


//    addCommonBtn({0.9,0.9}, "bk", [](){ Director::getInstance()->popScene(); });

    auto layer = Layer::create();
    this->addChild(layer);

    auto size = Director::getInstance()->getVisibleSize();

    auto camera = Camera::createPerspective(60, size.width/size.height, 0.1, 1000000);
    camera->setCameraFlag(CameraFlag::USER1);
    layer->addChild(camera);
    camera->setCameraMask((unsigned short)CameraFlag::USER1);
    camera->setPosition3D({0,0,50});
    camera->lookAt({0,0,0}, {0,1,0});
    _mainLayer = layer;
    _mainCamera = camera;

    const float loading_time = 1.5;

    auto hub = Sprite3D::create();
    hub->setPosition3D({0,0,0});
    hub->setCameraMask(_mainCamera->getCameraMask());
    hub->setScale(0.7);
    _mainLayer->addChild(hub);
    {

        auto node = PixelNode::create();
        node->setCameraMask(_mainCamera->getCameraMask());
        node->setPosition3D({0,0,0});
        node->configSopx("sopx/loading/rect.png.sopx");
        hub->addChild(node);
//        node->setScale(0.3);
//        node->setVisible(false);
//        node->setOpacity(0);
//        node->runAction();
    }

    {

        auto node = PixelNode::create();
        node->setCameraMask(_mainCamera->getCameraMask());
        node->setPosition3D({-25,0,0});
        node->configSopx("sopx/loading/content.png.sopx");
        hub->addChild(node);
//        node->setScaleX(25);
        node->runAction(Spawn::create(ScaleTo::create(loading_time, 50, 1, 1), MoveTo::create(loading_time, {0,0,0}), NULL));
        //        node->setScale(0.3);
        //        node->setVisible(false);
        //        node->setOpacity(0);
        //        node->runAction();
    }

    scheduleOnce([this](float dt) {

        this->loadingTask0();
    }, loading_time*0.2, "loading task 0");
    scheduleOnce([this](float dt) {

        this->loadingTask1();
    }, loading_time*0.5, "loading task 1");
    scheduleOnce([this](float dt){
        Director::getInstance()->replaceScene(QuestScene::create());
    },loading_time,"jump to quest");

    return true;
}
Scene* Chapter10_5::createScene()
{
    //cocos2d::Rect visibleRect = Director::getInstance()->getOpenGLView()->getVisibleRect();
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();
    auto winSize = Director::getInstance()->getWinSize();
    
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // create a scene
    // 'scene' is an autorelease object
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    auto scene = Scene::create();
    
    // add title
    auto label = LabelTTF::create("camera test", "Arial", 24);
    label->setPosition(Vec2(origin.x+visibleSize.width/2, origin.y+visibleSize.height/2).x,
                       Vec2(origin.x+visibleSize.width/2, origin.y+visibleSize.height).y - 30);
    
    scene->addChild(label, -1);
    
    //add the menu item for back to main menu
    label = LabelTTF::create("MainMenu", "Arial", 24);
    
    auto menuItem = MenuItemLabel::create(label);
    menuItem->setCallback([&](cocos2d::Ref *sender) {
        Director::getInstance()->replaceScene(Chapter10::createScene());
    });
    auto menu = Menu::create(menuItem, nullptr);
    
    menu->setPosition( Vec2::ZERO );
    menuItem->setPosition( Vec2( Vec2(origin.x+visibleSize.width, origin.y+visibleSize.height/2).x - 80, Vec2(origin.x+visibleSize.width/2, origin.y).y + 25) );
    
    scene->addChild(menu, 1);
    
    auto layer3D=Layer::create();
    scene->addChild(layer3D,2);
    
    std::string fileName = "orc.c3b";
    
    auto sprite = Sprite3D::create(fileName);
    sprite->setScale(5.f);
    sprite->setRotation3D(Vec3(0,180,0));
    sprite->setPosition( Vec2(origin.x+visibleSize.width/2, origin.y+visibleSize.height/2).x,
                        Vec2(origin.x+visibleSize.width/2, origin.y+visibleSize.height/2).y );
    
    // play animation
    auto animation = Animation3D::create(fileName);
    if (animation)
    {
        auto animate = Animate3D::create(animation);
        animate->setSpeed(1);
        sprite->runAction(RepeatForever::create(animate));
    }
    
    //add to scene
    layer3D->addChild(sprite);
    
    // add camera
    auto camera=Camera::createPerspective(60, (GLfloat)winSize.width/winSize.height, 1, 1000);
    camera->setCameraFlag(CameraFlag::USER1);// set camera flag
    camera->setPosition3D(Vec3(0, 0, 230) + sprite->getPosition3D());
    camera->lookAt(sprite->getPosition3D(), Vec3(0,1,0));
    
    // create camera action
    auto action = MoveBy::create(3, Vec2(100, 0));
    auto action_back = action->reverse();
    auto action1 = MoveBy::create(3, Vec2(0, 100));
    auto action_back1 = action1->reverse();
    auto seq = Sequence::create( action, action_back, action1, action_back1, nullptr );
    
    // run camera action
    camera->runAction( RepeatForever::create(seq) );
    
    layer3D->addChild(camera);
    
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // set camera mask
    // when node's camera-mask & camer-flag result is true, the node is visible for this camera.
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    layer3D->setCameraMask(0x2);
    
    // return the scene
    return scene;
}
Exemplo n.º 12
0
bool LevelTwo::init()
{
	if (!Layer::init())
	{
		return false;
	}

	preloadAudio();
	//playAudio();

	//Audio stuff created here. 
	//CocosDenshion::SimpleAudioEngine::getInstance()->preloadBackgroundMusic("audio/main.mp3");
	CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic("audio/main.mp3", true);

	//GameState initial setting.
	//m_gameState = GameStates::PlaceGunTower;
	//Listeners for touch events created.
	auto listener = EventListenerTouchAllAtOnce::create();
	listener->onTouchesBegan = CC_CALLBACK_2(LevelTwo::onTouchesBegan, this);
	listener->onTouchesMoved = CC_CALLBACK_2(LevelTwo::onTouchesMoved, this);
	listener->onTouchesEnded = CC_CALLBACK_2(LevelTwo::onTouchesEnded, this);
	_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
	
	Size visibleSize = Director::getInstance()->getVisibleSize();
	Point origin = Director::getInstance()->getVisibleOrigin();

	bool dir;
	bool jump = true;
	bool removeTraps = false;
	bool addPlatfroms = false;

	//Edge body created. Adding screen Boundry. 
	/*auto edgeBody = PhysicsBody::createEdgeBox(visibleSize, PHYSICSBODY_MATERIAL_DEFAULT, 1);
	auto edgeNode = Node::create();
	edgeNode->setPosition(Point(2000 / 2 + origin.x, 2000 / 2 + origin.y));
	edgeNode->setPhysicsBody(edgeBody);
	this->addChild(edgeNode);
	*/
	//Pause Button Creation
	auto pauseItem =
		MenuItemImage::create("GameScreen/Pause_Button.png",
			"GameScreen/Pause_Button(Click).png",
			CC_CALLBACK_1(LevelTwo::activatePauseScene, this));

	//Set Pause button position
	pauseItem->setPosition(Point(pauseItem->getContentSize().width -
		(pauseItem->getContentSize().width / 4) + 20,
		visibleSize.height - pauseItem->getContentSize().height +
		(pauseItem->getContentSize().width / 4) - 20));
	pauseItem->setScale(2);
	//Attach the pause button to the screen
	auto menu = Menu::create(pauseItem, NULL);
	menu->setPosition(Point::ZERO);
	this->addChild(menu, 10);

	//.........................................................................................
	//DPad

	//LeftButton to move the player.
	auto leftbutton = ui::Button::create("GameScreen/leftButtonIdle.png",
		"GameScreen/leftbuttonActive.png");
	leftbutton->setPosition(Vec2(origin.x + visibleSize.width / 10,
		origin.y + visibleSize.height / 6));
	leftbutton->setScale(2);
	leftbutton->addTouchEventListener([&](Ref* sender, ui::Widget::TouchEventType type) {
		switch (type)
		{
		case ui::Widget::TouchEventType::BEGAN:
			//handleTouch(this);
			//player->getPhysicsBody()->applyForce(Vec2(1000, 0));
			//player->getPhysicsBody()->setDynamic(true);
			dir = true;
			if (player1Selected == true) {
				player->pMovement(player, dir);
			}
			if (player2Selected == true) {
				player2->p2Movement(player2, dir);
			}
			break;
		case ui::Widget::TouchEventType::ENDED:
			player->getPhysicsBody()->setVelocity(Vec2(0, 0));
			player2->getPhysicsBody()->setVelocity(Vec2(0, 0));
			break;
		default:
			break;
		}
	});
	this->addChild(leftbutton, 10);

	//RightButton to move the player.
	auto rightbutton = ui::Button::create("GameScreen/rightButtonIdle.png",
		"GameScreen/rightbuttonActive.png");
	rightbutton->setPosition(Vec2(origin.x + visibleSize.width / 6,
		origin.y + visibleSize.height / 6));
	rightbutton->setScale(2);
	rightbutton->addTouchEventListener([&](Ref* sender, ui::Widget::TouchEventType type) {
		switch (type)
		{
		case ui::Widget::TouchEventType::BEGAN:
			//handleTouch(this);
			//player->getPhysicsBody()->applyForce(Vec2(1000, 0));
			dir = false;
			if (player1Selected == true) {
				player->pMovement(player, dir);
			}
			if (player2Selected == true) {
				player2->p2Movement(player2, dir);
			}
			break;
		case ui::Widget::TouchEventType::ENDED:
			player->getPhysicsBody()->setVelocity(Vec2(0, 0));
			player2->getPhysicsBody()->setVelocity(Vec2(0, 0));
			break;
		default:
			break;
		}
	});
	this->addChild(rightbutton, 10);

	int stop;

	//JumpButton to move the player.
	auto jumpbutton = ui::Button::create("GameScreen/jumpButtonIdle.png",
		"GameScreen/jumpButtonActive.png");
	jumpbutton->setPosition(Vec2(origin.x + visibleSize.width - 100,
		origin.y + visibleSize.height / 6));
	jumpbutton->setScale(2);
	jumpbutton->addTouchEventListener([&](Ref* sender, ui::Widget::TouchEventType type) {
		switch (type)
		{
		case ui::Widget::TouchEventType::BEGAN:
			//handleTouch(this);
			CCLOG("Jump button has been pressed");
			//player->getPhysicsBody()->applyForce(Vec2(1000, 0));
			if (player1Selected == true) {
				CCLOG("I've entered the jump if statement!");
				player->pJump(p1Jumped, player);
				p1Jumped = true;
				playJumpSound = true;
			}
			if (player2Selected == true) {
				CCLOG("I've entered the jump if statement!");
				player2->p2Jump(p2Jumped, player2);
				p2Jumped = true;
				playJumpSound = true;
			}

			break;
		case ui::Widget::TouchEventType::ENDED:
			break;
		default:
			break;
		}
	});

	this->addChild(jumpbutton, 10);
	addEvents();
	/*TowerBase * base = TowerBase::create(Vec2(ptr->m_towerBaseX[i], ptr->m_towerBaseY[i]), m_gameState);
	m_towerBases.push_back(base);
	spritebatch->addChild(base, -5);*/

	//Player select
	auto p1Select =
		MenuItemImage::create("GameScreen/p1Idle.png",
			"GameScreen/p1Select.png",
			CC_CALLBACK_0(LevelTwo::playerOneSelected, this));
	p1Select->setScale(2);
	p1Select->setPosition(Vec2((origin.x + visibleSize.width / 2) - 20,
		origin.y + visibleSize.height / 10));
	//this->addChild(p1Select, 5);

	auto p2Select =
		MenuItemImage::create("GameScreen/p2Idle.png",
			"GameScreen/p2Select.png",
			CC_CALLBACK_0(LevelTwo::playerTwoSelected, this));
	p2Select->setScale(2);
	p2Select->setPosition(Vec2((origin.x + visibleSize.width / 2) + 20,
		origin.y + visibleSize.height / 10));

	auto selectMenu = Menu::create(p1Select, p2Select, NULL);
	selectMenu->setPosition(Point::ZERO);
	this->addChild(selectMenu, 5);

	//Player Stuff Just testing stuff. Cut me some slack, Man!
	//Player One creation g and attachment ot the scene
	//Check player.cpp for Physics details.
	player = Player::create();
	player->setPosition(Vec2(20, 400));
	this->addChild(player, 0);

	//Same comment applies for player two as player one!
	player2 = Player2::create();
	player2->setPosition(Vec2(70, 400));
	this->addChild(player2, 0);

	//BackGround
	addBackGroundSprite(visibleSize, origin);

	//Create the Tower base. I'll be repurposing these for my level bases! 
	//Needs to be done urgently! 
	createPlatforms();
	createTraps();
	//createEndGame();
	createEndGameJack();
	createEndGameJill();
	createButton();
	createRemovablePlats();
	createFlameEmiiter();

	//Camera stuff.........................................
	auto camScene = Camera::create();
	camScene->setCameraFlag(CameraFlag::USER1);

	//HUD layer
	auto hud = Layer::create();
	hud->addChild(p2Select, 10);
	hud->addChild(p1Select, 10);
	//hud->addChild(selectMenu, 10);
	hud->addChild(jumpbutton, 10);
	hud->addChild(rightbutton, 10);
	hud->addChild(leftbutton, 10);
	hud->addChild(menu, 10);
	hud->setCameraMask((unsigned short)CameraFlag::USER1);

	this->addChild(camScene);

	auto contactListener = EventListenerPhysicsContact::create();

	contactListener->onContactBegin = CC_CALLBACK_1(LevelTwo::onContactBegin, this);
	this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(contactListener, this);

	cameraTarget = Sprite::create();
	cameraTarget->setPosition(player->getPositionX(), player->getPositionY());

	this->addChild(cameraTarget);
	camera = Follow::create(cameraTarget, Rect::ZERO);
	
	camera->retain();
	this->runAction(camera);

	this->scheduleUpdate();

	return true;
}