cocos2d-x3.0打飞机学习之纠正上一篇的一个问题

声明:模仿偶尔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));
}

在GameLayer里包含PlaneLayer,这里我没有用全局对象,因为不是所有对象都应该有权限访问PlaneLayer。谁需要才给他。

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);
}

看到木有,我这里要显式调用 m_pPlaneLayer->autorelease();但代码有木有比之前的清晰,如果感觉木有,就忽略吧,个人喜好。 偷笑

你可能感兴趣的:(cocos2d-x3.0打飞机学习之纠正上一篇的一个问题)