- 创建Layer层的类
- T2LayerSprite.h
#pragma once
#include "cocos2d.h"
USING_NS_CC; class T2LayerSprite:public CCLayer
{
public:
static CCScene * scene();
CREATE_FUNC(T2LayerSprite);
bool init();
};
- T2LayerSprite.h
红色代码处是一个宏定义:
#define CREATE_FUNC(__TYPE__) \
static __TYPE__* create() \
{ \
__TYPE__ *pRet = new(std::nothrow) __TYPE__(); \
if (pRet && pRet->init()) \
{ \
pRet->autorelease(); \
return pRet; \
} \
else \
{ \
delete pRet; \
pRet = nullptr; \
return nullptr; \
} \
}
等同于:
static T1LayerAnchorPoint*create();
T1LayerAnchorPoint*T1LayerAnchorPoint::create()
{
T1LayerAnchorPoint *pRet = new T1LayerAnchorPoint();
if (pRet && pRet->init())
{
pRet->autorelease();
}
else
{
delete pRet;
pRet = NULL;
}
return pRet; }
调用顺序:scene->create->init->scene
2.T2LayerSprite.cpp
#include "T2LayerSprite.h" CCScene * T2LayerSprite::scene()
{
CCScene *scene = CCScene::create();
T2LayerSprite *layer = T2LayerSprite::create();
scene->addChild(layer);
return scene;
} bool T2LayerSprite::init()
{
CCLayer::init(); //加载背景
//获取背景资源,并设置大小
CCSprite *bg = CCSprite::create("spirit/background.jpg",CCRectMake(,,,));
//获取屏幕大小
auto winSize = CCDirector::sharedDirector()->getWinSize();
//设置锚点
bg->setAnchorPoint(ccp(, ));
//设置位置
bg->setPosition(ccp(,));
//添加背景资源
addChild(bg); //加载图片
CCImage *image = new CCImage();
//图片初始化
image->initWithImageFile("spirit/plant.png");
//创建2D纹理
CCTexture2D *texture = new CCTexture2D();
//纹理自动释放
texture->autorelease();
//纹理用图片初始化
texture->initWithImage(image);
//用纹理创建精灵
CCSprite *plant = CCSprite::createWithTexture(texture);//纹理
//设置位置
plant->setPosition(ccp(,winSize.height/));
//添加图片
addChild(plant); //加载一张大图在缓存里
//创建纹理
CCTexture2D *texture2 = CCTextureCache::sharedTextureCache()->addImage("spirit/bullet.png");
//用纹理初始化精灵
CCSprite *bullet = CCSprite::createWithTexture(texture2);
//设置位置
bullet->setPosition(ccp(, winSize.height / + ));
//添加
addChild(bullet); //加载一组帧
CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("spirit/zombie.plist");
//此方法是先获取帧再加载
//CCSpriteFrame *sf = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("z_1_attack_03.png");
//CCSprite* zombie = CCSprite::createWithSpriteFrame(sf);
//此方法是直接通过名字加载
CCSprite *zombie = CCSprite::createWithSpriteFrameName("z_1_attack_03.png");
//设置位置
zombie->setPosition(ccp(, winSize.height / ));
//添加
addChild(zombie); //创建动作
CCJumpBy *by = CCJumpBy::create(, ccp(, ), , );
//zombie精灵设置跳跃动作
zombie->runAction(CCRepeatForever::create(by)); //获取单个帧
CCSpriteFrame *frame = CCSpriteFrame::create("spirit/p_1_01.png", CCRectMake(, , , ));
//通过帧初始化精灵
CCSprite *sun = CCSprite::createWithSpriteFrame(frame);
//设置位置
sun->setPosition(, winSize.height / + );
//添加
addChild(sun);
return true;
}
运行截图: