这几天刚学习cocos2d-x-3.0beta2,把一些例子调试运行成功后,记一下以便回顾。
1、设置屏幕分辨率例句
auto eglView = EGLView::getInstance();
director->setOpenGLView(eglView);
//-----------------------------------
CCSize frameSize = eglView->getFrameSize();
// 设置 LsSize 固定值
Size lsSize = CCSizeMake(480, 320);
float scaleX = (float) frameSize.width / lsSize.width;
float scaleY = (float) frameSize.height / lsSize.height;
// 定义 scale 变量
float scale = 0.0f; // MAX(scaleX, scaleY);
if (scaleX > scaleY) {
// 如果是 X 方向偏大,那么 scaleX 需要除以一个放大系数,放大系数可以由枞方向获取,
// 因为此时 FrameSize 和 LsSize 的上下边是重叠的
scale = scaleX / (frameSize.height / (float) lsSize.height);
} else {
scale = scaleY / (frameSize.width / (float) lsSize.width);
}
CCLog("x: %f; y: %f; scale: %f", scaleX, scaleY, scale);
// 根据 LsSize 和屏幕宽高比动态设定 WinSize
eglView->setDesignResolutionSize(lsSize.width * scale, lsSize.height * scale, kResolutionNoBorder);
说明:由于设备屏幕大小分辨率有多种,为了统一同一资源使用,结合:kResolutionShowAll 与kResolutionNoBorder的特点,使用kResolutionNoBorder而不至于留黑边和过分裁截,建立一个比屏幕要小的空间,无用空间用背景色填充。 参考:http://www.ityran.com/archives/4018
2、导入一个图片到场景
Size winSize = Director::getInstance()->getWinSize();
Point origin = Director::getInstance()->getVisibleOrigin();
auto sp=Sprite::create("HelloWorld.png");
sp->setPosition(winSize.width/2,winSize.height/2);
addChild(sp);
3、执行多帧动画
Animation* an = Animation::create();
an->addSpriteFrameWithFileName("a.jpg");
an->addSpriteFrameWithFileName("CloseSelected.png");
an->addSpriteFrameWithFileName("HelloWorld.png");
an->setDelayPerUnit(0.5f / 3.0f);
an->setLoops(-1);
Animate* anim = Animate::create(an);
sp->runAction(anim);
4、执行单个动作
ActionInterval * moveBy = MoveTo::create(5,Point(100, 100));
sp->runAction( moveBy);
5、顺序执行多个动作
ActionInterval * moveBy = MoveTo::create(5,Point(100, 100));
ActionInterval * scale = ScaleBy::create(5, 0.5);
FiniteTimeAction * seq= Sequence::create(moveBy,DelayTime::create(2),scale,NULL);
sp->runAction(seq);
6、同时执行多个动作
FiniteTimeAction *actionforward = Spawn::create(DelayTime::create(2), CCJumpTo::create(4, Point(0, 0), 100, 20),RotateTo::create(4, 720), FadeTo::create(4,10), NULL);
sp->runAction(actionforward);
7、执行贝塞尔曲线例句
ccBezierConfig bezier;
bezier.controlPoint_1 = Point(0, winSize.height);
bezier.controlPoint_2 = Point(winSize.width, winSize.height);
bezier.endPosition = Point(winSize.width, 0);
ActionInterval *jumpDown = BezierBy::create(2, bezier);
FiniteTimeAction *action =Sequence::create(jumpDown,NULL);
sp->setPosition(0,0);
sp->runAction(action);
8、执行粒子系统 方法1
ParticleSystem* particle = ParticleSystemQuad::create("snow.plist");
particle->setPosition(Point(winSize.width,winSize.height));
particle->setBlendAdditive(true); //对粒子属性修改
addChild(particle);
9、执行粒子系统 方法2
ParticleSystem* particle2 = ParticleSystemQuad::create("snow.plist");
particle2->retain();
ParticleBatchNode *batch = ParticleBatchNode::createWithTexture(particle2->getTexture());
batch->addChild(particle2);
batch->setPosition(winSize.width,winSize.height);
addChild(batch, 10);
particle2->release();
10、读取地图
auto pTiledMap=TMXTiledMap::create("tilemap.tmx"); //tmx 及相应png放在Resources文件里
addChild(pTiledMap,-10);
11、监听事件例句
auto listener1 = EventListenerTouchOneByOne::create();
listener1->setSwallowTouches(true);
listener1->onTouchBegan = [](Touch* touch, Event* event)
{
auto target = static_cast<Sprite*>(event->getCurrentTarget());//获取的当前触摸的目标
Point locationInNode = target->convertToNodeSpace(touch->getLocation());
Size s = target->getContentSize();
Rect rect = Rect(0, 0, s.width, s.height);
if (rect.containsPoint(locationInNode))//判断触摸点是否在目标的范围内
return true;
else
return false;
};
//拖动精灵移动
listener1->onTouchMoved = [](Touch* touch, Event* event)
{
auto target = static_cast<Sprite*>(event->getCurrentTarget());
target->setPosition(target->getPosition() + touch->getDelta());
};
listener1->onTouchEnded = [=](Touch* touch, Event* event)
{
_eventDispatcher->removeEventListeners(EventListener::Type::TOUCH_ONE_BY_ONE);
//删除触摸监听 只能移一次
};
//将触摸监听添加到eventDispacher中去
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1,sp);
12、 响应菜单事件
auto closeItem = MenuItemImage::create("CloseNormal.png", "CloseSelected.png",CC_CALLBACK_1(GameLayer::menuCloseCallback, this));
void HelloWorld::menuCloseCallback(Object* pSender)
{
Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}
13、读精灵动作与动画
SpriteFrameCache::getInstance()->addSpriteFramesWithFile("pd_sprites.plist");
auto m_pSpriteNodes = SpriteBatchNode::create("pd_sprites.pvr.ccz");
auto sp=Sprite::create();
sp->setPosition(winSize.width/2,winSize.height/2);
addChild(sp);
Animation *pIdleAnim = this->createAnimation("hero_walk_%02d.png", 7, 12);
sp->runAction(RepeatForever::create(Animate::create(pIdleAnim)));
auto sp1=Sprite::create();
sp1->setPosition(winSize.width/4,winSize.height/2);
addChild(sp1);
Animation *pIdleAnim1 = this->createAnimation("hero_attack_00_%02d.png", 3, 10);
sp1->runAction(Sequence::create(Animate::create(pIdleAnim1),createIdleCallbackFunc(), NULL));
sp1->setTag(1);
Animation* GameLayer::createAnimation(const char* formatStr, int frameCount, int fps)
{
Vector<SpriteFrame*> pFrames ;
for(int i = 0; i < frameCount; ++ i)
{
const char* imgName = String::createWithFormat(formatStr, i)->getCString();
SpriteFrame *pFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(imgName);
pFrames.pushBack(pFrame);
}
return Animation::createWithSpriteFrames(pFrames, 1.0f / fps);
}
CallFunc* GameLayer::createIdleCallbackFunc()
{
return CallFunc::create(CC_CALLBACK_0(GameLayer::runIdleAction, this));
}
void GameLayer::runIdleAction()
{
Animation *pIdleAnim1 = this->createAnimation("hero_attack_00_%02d.png", 3, 10);
//CCNode *node = CCDirector::sharedDirector()->getRunningScene()->getChildByTag(1);
Node *node = getChildByTag(1);
node->runAction(Sequence::create(DelayTime::create(1),Animate::create(pIdleAnim1),createIdleCallbackFunc(), NULL));
}
//参考了 http://codingnow.cn/cocos2d-x/1295.html
14、场景切换
Scene *pScene = GameScene::createScene();
Director::getInstance()->replaceScene(CCTransitionJumpZoom::create(1.0f,pScene ));
15、物理空间模拟
(1)建立空间场景
auto scene = Scene::createWithPhysics();
//DrawMask参数可以选择打开绘制哪些部分比如,Joint、Shape、Contact等等
scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_NONE);
Size visibleSize = Director::getInstance()->getVisibleSize();
auto body = PhysicsBody::createEdgeBox(visibleSize, PHYSICSBODY_MATERIAL_DEFAULT, 3);
auto edgeNode = Node::create();
edgeNode->setPosition(Point(visibleSize.width/2,visibleSize.height/2));
edgeNode->setPhysicsBody(body);
scene->addChild(edgeNode);
(2)空间场景添加到层中
auto layer = HelloWorld::create();
layer->setPhyWorld(scene->getPhysicsWorld());
(3)监听碰撞
auto contactListener = EventListenerPhysicsContact::create();
contactListener->onContactBegin = CC_CALLBACK_2(HelloWorld::onContactBegin, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this);
(4)碰撞事件
bool HelloWorld::onContactBegin(EventCustom *event, const PhysicsContact& contact)
{
auto sp = (Sprite*)contact.getShapeA()->getBody()->getNode();
int tag = sp->getTag();
CCLOG("onContactBegin: %d", tag);
return true;
}
(5)设置精灵body
auto sprite = Sprite::create("circle.png");
sprite->setTag(1);
auto body = PhysicsBody::createCircle(sprite->getContentSize().width / 2);
sprite->setPhysicsBody(body);
sprite->setPosition(p);
this->addChild(sprite);
(6)可以设置空间边框线
PhysicsWorld* m_world; // 在头文件定义
//m_world->setSpeed(2.0);
//m_world->setGravity(Point(0,-100));
if(m_world->getDebugDrawMask() != PhysicsWorld::DEBUGDRAW_NONE) {
m_world->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_NONE);
} else {
m_world->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);
}
16、定时器schedule,scheduleUpdate,scheduleOnce
this->schedule( schedule_selector(HelloWorld::moveBackground),2); //每2秒执行函数moveBackground
void HelloWorld::moveBackground(float dt)
{
CCLOG("%f",dt);
this->unschedule(schedule_selector(HelloWorld::moveBackground)); //停止执行自定义定时器函数
}
//scheduleOnce 执行一次
//scheduleUpdate 每帧执行 update函数,需重载Object里 virtual void update(float dt)
//this->unscheduleUpdate();停止默认定时器
//this->unscheduleAllSelectors(); 停止所有定时器
还在学习中,找到经典,继续添加中……