声明:模仿偶尔e网事童鞋。
虽然改变了代码风格,但有一个关键点忽略了,就是autorelease。cocos2d-x一般用静态的create函数来搞,里面封装了autorelease。
现在我这种写法需要在外部显式调用。
#pragma once #include "cocos2d.h" USING_NS_CC; class PlaneLayer : public Layer { public: PlaneLayer(); }; #include "PlaneLayer.h" PlaneLayer::PlaneLayer() { Layer::init(); CCSize winSize = CCDirector::sharedDirector()->getWinSize(); auto spriteFrameCache = cocos2d::SpriteFrameCache::sharedSpriteFrameCache(); spriteFrameCache->addSpriteFramesWithFile("shoot.plist"); Sprite* plane = Sprite::createWithSpriteFrame(spriteFrameCache->spriteFrameByName("hero1.png")); plane->setPosition(ccp(winSize.width/2, plane->getContentSize().height/2)); addChild(plane); Blink* blink = Blink::create(1,3); CCAnimation* animation = CCAnimation::create(); animation->setDelayPerUnit(0.1); animation->addSpriteFrame(spriteFrameCache->spriteFrameByName("hero1.png")); animation->addSpriteFrame(spriteFrameCache->spriteFrameByName("hero2.png")); CCAnimate* animate = CCAnimate::create(animation); plane->runAction(blink); plane->runAction(CCRepeatForever::create(animate)); }
class GameLayer : public cocos2d::Layer { public: GameLayer(); void backGroupMove(float dt); private: cocos2d::Sprite* m_pBackground1; cocos2d::Sprite* m_pBackground2; PlaneLayer* m_pPlaneLayer; };
GameLayer::GameLayer() { cocos2d::Layer::init(); auto spriteFrameCache = cocos2d::SpriteFrameCache::sharedSpriteFrameCache(); spriteFrameCache->addSpriteFramesWithFile("shoot_background.plist"); m_pBackground1= Sprite::createWithSpriteFrame(spriteFrameCache->getSpriteFrameByName("background.png")); m_pBackground1->setPosition(ccp(0,0)); m_pBackground1->setAnchorPoint(ccp(0,0)); addChild(m_pBackground1); m_pBackground2= Sprite::createWithSpriteFrame(spriteFrameCache->getSpriteFrameByName("background.png")); m_pBackground2->setPosition(ccp(0,m_pBackground2->getContentSize().height-5)); m_pBackground2->setAnchorPoint(ccp(0,0)); addChild(m_pBackground2); schedule(schedule_selector(GameLayer::backGroupMove), 0.01f); m_pPlaneLayer = new PlaneLayer; m_pPlaneLayer->autorelease(); addChild(m_pPlaneLayer); }