cocos2d-x代码练习

/****************************************************************************
Copyright © 2017-2018 Xiamen Yaji Software Co., Ltd.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#include “HelloWorldScene.h”
#include “SimpleAudioEngine.h”
#include
#include “ui/CocosGUI.h”
#include “ui/UIButton.h”
#include “SimpleAudioEngine.h”

using namespace CocosDenshion;
using namespace ui;
using namespace std;
USING_NS_CC;

Scene* HelloWorld::createScene()
{
return HelloWorld::create();
}

// Print useful error message instead of segfaulting when files are not there.
static void problemLoading(const char* filename)
{
printf(“Error while loading: %s\n”, filename);
printf(“Depending on how you compiled you might have to add ‘Resources/’ in front of filenames in HelloWorldScene.cpp\n”);
}

// on “init” you need to initialize your instance
bool HelloWorld::init()
{
//
// 1. super init first
if ( !Scene::init() )
{
return false;
}

auto visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();

/
// 2. add a menu item with "X" image, which is clicked to quit the program
//    you may modify it.

// add a "close" icon to exit the progress. it's an autorelease object
auto closeItem = MenuItemImage::create(
                                       "CloseNormal.png",
                                       "CloseSelected.png",
                                       CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));

if (closeItem == nullptr ||
    closeItem->getContentSize().width <= 0 ||
    closeItem->getContentSize().height <= 0)
{
    problemLoading("'CloseNormal.png' and 'CloseSelected.png'");
}
else
{
    float x = origin.x + visibleSize.width - closeItem->getContentSize().width/2;
    float y = origin.y + closeItem->getContentSize().height/2;
    closeItem->setPosition(Vec2(x,y));
}

// create menu, it's an autorelease object
auto menu = Menu::create(closeItem, NULL);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);

/
// 3. add your codes below...

// add a label shows "Hello World"
// create and initialize a label

auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24);
if (label == nullptr)
{
    problemLoading("'fonts/Marker Felt.ttf'");
}
else
{
    // position the label on the center of the screen
    label->setPosition(Vec2(origin.x + visibleSize.width/2,
                            origin.y + visibleSize.height - label->getContentSize().height));

    // add the label as a child to this layer
    this->addChild(label, 1);
}

// add "HelloWorld" splash screen"
auto sprite = Sprite::create("HelloWorld.png");
if (sprite == nullptr)
{
    problemLoading("'HelloWorld.png'");
}
else
{
    // position the sprite on the center of the screen
    sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));

    // add the sprite as a child to this layer
    this->addChild(sprite, 0);
}
return true;

}

void HelloWorld::menuCloseCallback(Ref* pSender)
{
//Close the cocos2d-x game scene and quit the application
Director::getInstance()->end();

/*To navigate back to native iOS screen(if present) without quitting the application  ,do not use Director::getInstance()->end() as given above,instead trigger a custom event created in RootViewController.mm as below*/

//EventCustom customEndEvent("game_scene_close_event");
//_eventDispatcher->dispatchEvent(&customEndEvent);

auto sp = AutoPolygon::generatePolygon("test.png");
auto sprite = Sprite::create(sp);

auto moveTo = MoveTo::create(2, Vec2(50,50));
auto moveBy = MoveBy::create(2, Vec2(0,30));
sprite->runAction(moveTo);
sprite->setPosition(50,50);
cout<<sprite->getPositionY();

auto delay = DelayTime::create(1);
auto seq = Sequence::create(moveBy,delay,moveTo,nullptr);
sprite->runAction(seq);

auto rotate = RotateTo::create(2.0f, 20.0f);
sprite->runAction(rotate);

auto fadeIn = FadeIn::create(2.0f);
auto fadeOut = FadeOut::create(2.0f);
auto fseq = Sequence::create(fadeIn,delay,fadeOut,nullptr);
sprite->runAction(fseq);

auto tintTo = TintTo::create(2.0f, 124.0f,122.0f,124.0f);
auto tintBy = TintBy::create(2.0f, 124.0f,122.0f,124.0f);

//Animation animate 创建帧动画
Vector<SpriteFrame*> aniFrames;
/**aniFrames.reserve(5);
aniFrames.pushBack(SpriteFrame::create("Blue_Front1.png", Rect(0,0,65,81)));
aniFrames.pushBack(SpriteFrame::create("Blue_Front2.png", Rect(0,0,65,81)));
aniFrames.pushBack(SpriteFrame::create("Blue_Front3.png", Rect(0,0,65,81)));
aniFrames.pushBack(SpriteFrame::create("Blue_Front4.png", Rect(0,0,65,81)));
aniFrames.pushBack(SpriteFrame::create("Blue_Front5.png", Rect(0,0,65,81)));
Animation* animation = Animation::createWithSpriteFrames(aniFrames, 0.1f);
Animate* animate = Animate::create(animation);
sprite->runAction(RepeatForever::create(animate));*/

auto jump = JumpBy::create(0.5, Vec2(0, 0), 100, 1);
auto rotate = RotateTo::create(2.0f, 10);
auto callbackJump = CallFunc::create([](){
   log("Jumped!");
});
auto seq = Sequence::create(jump, callbackJump, rotate, nullptr);
sprite->runAction(seq->reverse());

auto spawn = Spawn::createWithTwoActions(jump, rotate);
sprite->runAction(spawn);

auto hero = Sprite::create("hero.png");
auto enemy = Sprite::create("enemy.png");

hero->runAction(jump);
enemy->runAction(jump->clone());

auto dir = Director::getInstance();
Size size = dir->getVisibleSize();
auto scene = Scene::create();
auto lbl = Label::createWithTTF("start", "test.ttf",24);
lbl->setPosition(size.width * 0.5, size.height);
scene->addChild(lbl);

auto tree = Sprite::create("tree.png");
tree->setPosition(100,100);
scene->addChild(tree);
Director::getInstance()->runWithScene(scene);//只用于运行第一个场景

auto scene2 = Scene::create();
Director::getInstance()->replaceScene(TransitionFade::create(1.0f, scene2));//场景转换特效
Director::getInstance()->pushScene(TransitionFlipX::create(1,scene2));
Director::getInstance()->popScene();

TTFConfig ttfConfig;
auto lbl2 = Label::createWithSystemFont("my label text", "Arial", 16);
lbl2->enableShadow();
lbl2->enableGlow(Color4B::GREEN);
lbl2->enableOutline(Color4B::BLACK);

auto closeItem = MenuItemImage::create("CloseNormal.png", "CloseSelected.png",
CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));

auto menu = Menu::create(closeItem, NULL);
this->addChild(menu, 1);

//auto func = [](){log("lambda");};
//func();

auto button = Button::create("normal_image.png", "selected_image.png", "disabled_image.png");
button->setTitleText("START GAME");

button->addTouchEventListener([&](Ref* sender, Widget::TouchEventType type){
	switch(type)
	{
		case Widget::TouchEventType::BEGAN:
			log("touch began");
			break;
		case Widget::TouchEventType::ENDED:
			log("touch end");
			break;
		default:
			break;
	}
});
this->addChild(button);

//进度条
auto loading = LoadingBar::create("loadingBar.png");
loading->setDirection(LoadingBar::Direction::RIGHT);
loading->setPercent = 30;
this->addChild(loading);

auto slider = Slider::create();
slider->loadBarTexture("bar.png");
slider->loadProgressBarTexture("progress.png");
slider->loadSlidBallTextures("ball.png");
this->addChild(slider);

auto textfield = TextField::create("please enter your name:","Arial", 24);
textfield->setPasswordEnabled(true);
textfield->setMaxLength(15);
this->addChild(textfield);

auto map = TMXTiledMap::create("map.tmx");
auto layer = map->getLayer("Layer0");
auto tile = layer->getTileAt(Vec2(1,63));
unsigned int gid = layer->getTileGIDAt(Vec2(0,63));

addChild(map,0,99);

//添加火焰粒子特效
auto particleSystem = ParticleSystem::create("particle.plist");
auto fire = ParticleFire::create();
fire->setDuration(ParticleSystem::DURATION_INFINITY);
fire->setEmitterMode(ParticleSystem::Mode::RADIUS);
fire->setStartRadius(100.0f);
fire->setStartRadiusVar(0);
fire->setEndRadius(ParticleSystem::START_RADIUS_EQUAL_TO_END_RADIUS);
fire->setEndRadiusVar(0);
addChild(fire, 10);

auto node = ParallaxNode::create();
auto background = Sprite::create("background.png");
auto middleLayer = Sprite::create("mid.png");
auto topLayer = Sprite::create("top.png");
node->addChild(background, -1, Vec2(2.0f,1.0f), Vec2::ZERO);
node->addChild(middleLayer, 0, Vec2(3.0f, 2.0f), Vec2(0, 200));
node->addChild(topLayer, 1, Vec2(4.0f,2.0f), Vec2(200, 800));

button->addClickEventListener([&](Ref* sender, Widget::TouchEventType type){
	log("click event");
});

auto listener1 = EventListenerTouchOneByOne::create();
auto listener2 = EventListenerTouchAllAtOnce::create();
auto listener3 = EventListenerMouse::create();
auto listener4 = EventListenerKeyboard::create();
auto listener5 = EventListenerAcceleration::create([](){});
auto listener6 = EventListenerFocus::create();

listener1->setSwallowTouches(true);
listener1->onTouchBegan = [](Touch* touch, Event* event){
	return true;
};

listener1->onTouchMoved = [](Touch* touch, Event* event){
	log("touch move");
};

listener2->onTouchesEnded = [=](Touch* touch, Event* event){
	log("touch end");
};

_eventDispatcher->addEventListenerWithFixedPriority(listener1,1);
_eventDispatcher->addEventListenerWithFixedPriority(listener2,2);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener3,this);
Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(listener4,3);

listener4->onKeyPressed = CC_CALLBACK_2(HelloWorld::keyPressHandler,this);

Device::setAccelerometerEnabled(true);
auto acceListener = EventListenerAcceleration::create(CC_CALLBACK_2(HelloWorld::onAcceleration,this));
_eventDispatcher->addEventListenerWithSceneGraphPriority(acceListener,this);


//自定义事件

auto userListener = EventListenerCustom::create("test_event", [=](EventCustom* event){
	string str("test event");
	char* buf = static_cast<char*>(event->getUserData());
	str += buf;
});
_eventDispatcher->addEventListenerWithSceneGraphPriority(userListener,this);

static int count = 0;
++count;	
char* buf[10];
sprintf(*buf, "%d", count);
EventCustom event("test_event");
event.setUserData(buf);
_eventDispatcher->dispatchEvent(&event);


auto sp1 = Sprite::create("sp.png");
auto sp2 = Sprite::create("sp.png");
auto sp3 = Sprite::create("sp.png");

_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, sp1);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1->clone(),sp2);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1->clone(),sp3);
_eventDispatcher->removeEventListener(listener1);


auto s = Director::getInstance()->getWinSize();
auto camera = Camera::createPerspective(60, (GLfloat)s.width/s.height,1,1000);
camera->setPosition3D(Vec3(0,100,100));
camera->lookAt(Vec3(0,0,0),Vec3(0,1,0));
addChild(camera);

auto orth_camera = Camera::createOrthographic(s.width,s.height,1,1000);

//node->setCameraMask(CameraFlag::USER1);
camera->setCameraFlag(CameraFlag::USER1);

//自然光
auto light = AmbientLight::create(Color3B::RED);
this->addChild(light);

//定向光
auto dlight = DirectionLight::create(Vec3(-1.0f,-1.0f,0.0f),Color3B::RED);
this->addChild(dlight);

//点光源
auto plight = PointLight::create(Vec3(0.0f,0.0f,0.0f),Color3B::RED, 1000.0f);
this->addChild(plight);

//聚光
auto spotLight = SpotLight::create(Vec3(-1.0f, -1.0f, 0.0f), Vec3(0.0f, 0.0f, 0.0f),
Color3B::RED, 0.0, 0.5, 10000.0f) ;
this->addChild(spotLight);

auto player = Sprite::create("player.png");
auto component = Component::create(); //ComponentLua::


//物理引擎
auto physicsBody = PhysicsBody::createBox(Size(65.0f,81.0f), PhysicsMaterial(0.1f,1.0f,0.0f));
physicsBody->setDynamic(false);

auto hero = Sprite::create("hero.png");
hero->addComponent(physicsBody);

auto concatListener = EventListenerPhysicsContact::create();
concatListener->onContactBegin = [](PhysicsContact* contact){};
_eventDispatcher->addEventListenerWithSceneGraphPriority(concatListener,this);


auto physicsBody = PhysicsBody::createBox(Size(65.0f, 81.0f),
                    PhysicsMaterial(0.1f, 1.0f, 0.0f));
physicsBody->setDynamic(false);

auto sprite = Sprite::create("whiteSprite.png");
auto s_centre = Vec2(s.width,s.height);
sprite->setPosition(s_centre);
addChild(sprite);

sprite->addComponent(physicsBody);

const int DRAG_BODYS_TAG = 1;

for (int i = 0; i < 5; ++i)
{
	physicsBody = PhysicsBody::createBox(Size(65.0f, 81.0f),
                  PhysicsMaterial(0.1f, 1.0f, 0.0f));
	physicsBody->setGravityEnable(false);
	physicsBody->setVelocity(Vec2(cocos2d::random(-500,500),
            cocos2d::random(-500,500)));
	physicsBody->setTag(DRAG_BODYS_TAG);

	sprite = Sprite::create("blueSprite.png");
	sprite->setPosition(Vec2(s_centre.x + cocos2d::random(-300,300),
            s_centre.y + cocos2d::random(-300,300)));
	sprite->addComponent(physicsBody);
	addChild(sprite);
}

auto func = [](PhysicsWorld& world, PhysicsShape& shape, void* userData)->bool{
	return true;
};

scene->getPhysicsWorld()->queryRect(func, Rect(0,0,200,200),nullptr);

//Director::getInstance()->getRunningScene()->getPhysics3DWorld()->setDebugDrawEnable(true);
//Director::getInstance()->getRunningScene()->getPhy

auto audio = SimpleAudioEngine::getInstance();
audio->playBackgroundMusic("music.mp3",true);//循环播放
audio->playBackgroundMusic("music.mp3",false);//单词播放

int effId = audio->playEffect("music.mp3",false,1.0f,1.0f,1.0f);

audio->pauseBackgroundMusic();
audio->pauseAllEffects();
audio->pauseEffect(effId);//暂停音效

audio->stopBackgroundMusic();
audio->stopAllEffects();
audio->stopEffect(effId);

audio->resumeBackgroundMusic();
audio->resumeAllEffects();
audio->resumeEffect(effId);

audio->preloadBackgroundMusic("music.mp3");
audio->preloadEffect("music.mp3");
audio->unloadEffect("music.mp3");
audio->setBackgroundMusicVolume(0.5f);
audio->setEffectsVolume(0.5f);

auto files = FileUtils::getInstance();
string str = "";
if (files->isFileExist("test.txt"))
{
	log("file exist");
	str = files->getStringFromFile("test.txt");
}

if (files->isDirectoryExist("game/src/img"))
{
	log("directory exist");
}
else
{
	files->createDirectory("game/src/img");
}

//auto programState = GLProgram::createWithByteArrays();
//sprite->setGLProgramState(programState);

Material* material = Material::createWithFilename("material/3d_effect.material");
auto sprite3d = Sprite3D::create();
sprite3d->setMaterial(material);
material->setTechnique("normal");
material->setTechnique("normal");

}

void HelloWorld::onAcceleration(Acceleration* acc, Event* event)
{
log(“accelerate”);
}

void HelloWorld::keyPressHandler(EventKeyboard::KeyCode keycode, Event* event)
{
log(“keyboard event”);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值