Director::getInstance()->runWithScene(scene);
Director::getInstance()->replaceScene(scene);//切换场景
Director::getInstance()->replaceScene(TransitionSlideInT::create(3.0f,scene));//切换场景 会释放场景
Director::getInstance()->pushScene(scene); //新的场景会覆盖当前场景
Director::getInstance()->popScene(scene); //新场景释放 恢复旧场景
Label * label =Label::create("I m label","Arial",30);
MenuItemImage
MenuItemLabel
Menu * menu =Menu::create(menuItem1,menuItem2);
menu->alignItemsVertically(); //菜单垂直方向上自动排列
menu_selector(HelloWorld::menuCloseCallback);//给menu设置回调
Ref cocos2sd-x引擎基类 大部分类都继承自它 autorelease();
Node 拥有简单功能的类 update
Layer 继承node 拥有多种功能 屏幕触摸监听等
Value Vector Map
Value value = Value("1000");
value.asString().c_str();
整数 浮点数 字符串之间的转换
Vector<Label *>vec;
for(auto lab:vec){ //可以遍历每一个对象
}
size()
at()
front() 第一个对象
back() 最后一个对象
pushBack()
eraseObject(object)
erase(index);
clear() 清空
Map<int,Label*> map;
map.insert(i,lab);
log()
#include "SimpleAudioEngine.h"
CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic("filePath",loop);
CocosDenshion::SimpleAudioEngine::getInstance()->playEffect("filePath");
#include "ui\UIScale9Sprite.h"
using namespace ui;
//studio
#include "cocostudio/CocoStudio.h"
auto layer = CSLoader::getInstance()->createNode("MainScene.csb");
JumpBy * jumpBy = JumpBy::create(3.0f,Point(50,1),100,1);
RepeatForever * repeateForver =RepeatForver::create(jumpBy);//无限次
Repeat * repeatAction =Repeat::create(jumpBy,3); //有限次
sprite->runAction(repeatActon);
//一起播放
Action actions =Spawn::create();//最后一个参数null
Sequence 一个接一个
sprite->setScale(20);
};
CallFunc * callfunc = CallFunc::create(func);
this->runAction(callfunc); //看不见得动作 与 sequence 配合获得动作结束回调
lambad
[] 表示开始一个lambda函数
() 符号 里面填写函数的参数
{} 函数题内容
&截取外部作用域所有变量 (不能用局部变量)
= 浅拷贝所有外部变量
[=,&value1] 针对value1 引用其他变量忽略
//单点事件监控
auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);
listener->onTouchBegan = [](Touch* touch,Event * event) {
return true;
};
//node被释放的时候 监听事件也会被释放
//多个node时 根据node层次返回 越上面越先 后面this是监听对象 node
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
touch->getLocation();//3D
touch->getLocationInView();//2d
Director::getInstance()->convertToGL(pos);//转到笛卡尔坐标系
auto target = static_cast<Sprite*>(event->getCurrentTarget());
aotu pos = Director::getInstance()->convertToGL(touch->getLocationInView());
sprite->setOpacity(100); 设置透明度
//多点触控
auto listener2 = EventListenerTouchAllAtOnce::create();
listener2->onTouchesBegan = [](const std::vector<Touch*>&touches,Event * event) {
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener2, this);
Rect rect = sprite->getBoundingBox();
rect.containsPoint(pos); //点与rect是否交集
Auto-batching
如果globalZOrder 相同则是连续的 针对全局的控制
否则localZOrder 相同是连续的 针对节点的子节点的绘制顺序
否则 orderOfArrival 相同 则是连续的 当localZOrder相同时 调整节点的绘制顺序
(精灵还有个添加顺序)
globalZOrder localZOrder orderOfArrival 同一个图片的精灵有一个要相同且不与别的重复(即实现同图片其 globalZOrder localZOrder orderOfArrival 连续)
SpriteBatchNode类 与Auto-batching 相同效果 但是只能把 sprite添加在其上 不方便
SpriteBatchNode *bathNode = SpriteBatchNode::create("CloseNormal.png");
this->addChild(bathNode);
for (int i = 0; i < 14100; i++) {
Sprite * sprite = Sprite::create("CloseNormal.png");
sprite->setPosition(Point(CCRANDOM_0_1()*visibleSize.width+sprite->getContentSize().width, CCRANDOM_0_1()*visibleSize.height));
bathNode->addChild(sprite);
}
//截取部分
按屏幕坐标
Sprite * sp1 = Sprite::createWithSpriteFrame(SpriteFrame::create("HelloWorld.png", Rect(0, 0, 50, 120)));
//从有 plist文件的大图中 获取 小图 TexturePacker工具 节省绘制
SpriteFrameCache * frameCache = SpriteFrameCache::getInstance(); //缓存池
frameCache->addSpriteFramesWithFile("girls.plist", "girls.png");
Sprite * sp = Sprite::createWithSpriteFrameName("sprite2.png");
//动画 SpriteFrame
Vector<SpriteFrame*>frameVec;
for (int i = 0; i < 15; i++) {
SpriteFrame * frame = SpriteFrame::create(StringUtils::format("run%d.png", i), Rect(0, 0, 100, 100));
frameVec.pushBack(frame);
}
Animation * animation = Animation::createWithSpriteFrames(frameVec);
animation->setLoops(-1);
animation->setDelayPerUnit(0.1f);
Animate * action = Animate::create(animation);
sprite->runAction(action);
auto animation = Animation::create();
for (int i = 1; i<15; i++)
{
char szName[100] = { 0 };
sprintf(szName, "Images/grossini_dance_%02d.png", i);
animation->addSpriteFrameWithFile(szName);
}
animation->setDelayPerUnit(2.8f / 14.0f);
animation->setRestoreOriginalFrame(true); //是否回到初始帧
auto action = Animate::create(animation);
sprite->runAction(Sequence::create(action, action->reverse(), NULL));
//动画 有plist
SpriteFrameCache* frameCache = SpriteFrameCache::getInstance();
frameCache->addSpriteFramesWithFile("boys.plist", "boys.png");
Vector<SpriteFrame*>frameVec;
for (int i = 0; i < 15; i++) {
SpriteFrame * frame =frameCache->getSpriteFrameByName(StringUtils::format("run%d.png", i));
frameVec.pushBack(frame);
}
Animation * animation = Animation::createWithSpriteFrames(frameVec);
animation->setLoops(-1);
animation->setDelayPerUnit(0.1f);
Animate * action = Animate::create(animation);
sprite->runAction(action);
//辅助类创建动画 这个更加通用
//名字前缀 delay loops
//需要加载图片到缓存池
SpriteFrameCache* frameCache = SpriteFrameCache::getInstance();
frameCache->addSpriteFramesWithFile("boys.plist", "boys.png");
Animation * animation =AnimationUtil::createWithSingleFrameName("run",0.1f,-1);
sprite->runAction(Animate::create(animation));
//前缀 动画帧数 delay loops
AnimationUtil::createWithSingleFrameNameAndNum();
//-------------------------瓦片地图---- Tiled Map Editor---------------
TMXTiledMap * map = TMXTiledMap::create("level01.tmx");
this->addChild(map);
//得到一个标记点坐标
ValueMap playerPointMap = objectGroup->getObject("PlayerPoint");
float x = playerPointMap.at("x").asFloat;
float y = playerPointMap.at("y").asFloat;
//得到地图方块数量
Size mapNum= map->getMapSize();
//地图单个格子大小
Size titleSize = map->getTileSize();
//map大小
Size mapSize = Size(mapNum.width*titleSize.width,
mapNum.height * titleSize.height
);
//----------------------------------------------------一段以主角为中心的代码--------------------------------
//主角为中心点
Size visibleSize = Director::getInstance()->getVisibleSize();
//主角坐标
Point spritePos = sprite->getPosition();
float x = std::max(spritePos.x, visibleSize.width * 0 / 5);
float y= std::max(spritePos.y, visibleSize.height * 0 / 5);
x = std::min(x, mapSize.width - visibleSize.width*0.5f);
y = std::min(y, mapSize.height - visibleSize.height*0.5f);
//目标点
Point destPos = Point(x, y);
//屏幕中
Point centerPos = Point(visibleSize.width*0.5, visibleSize.height*0.5);
//屏幕到目标点的距离
Point viewPos = centerPos - destPos;
this->getParent()->setPosition(viewPos);
//如果移动出现黑边
Director::getInstance()->setProjection(Director::Projection::_2D);加上这句话
//---------定时器--------------
virtual void update(float dt);
this->scheduleUpdate();
this->unscheduleUpdate();
//--------自定义定时器--------
void mutUpdate(float dt);
//每帧都执行
this->schedule(schedule_selector(HelloWorld::mutUpdate));
this->schedule(schedule_selector(HelloWorld::mutUpdate),2.0f);//2秒一次
this->unschedule(schedule_selector(HelloWorld::mutUpdate));
//停止所有定时器
this->unscheduleAllSelectors();
//一次定时器
this->scheduleOnce(schedule_selector(HelloWorld::mutUpdate),2.0f); //2秒后执行
//计数器加一
sprite->retain();
sprite->release();
//本地存取数据
UserDefault::getInstance()->setBoolForKey("22",true);
UserDefault::getInstance()->getBoolForKey("22",false); //false 没有时的 默认值
csv文件
json文件
https://sourceforge.net/projects/jsoncpp
src/lib_json 和 include/json 里的文件 放到class/json文件夹下
//读
#include"Classes\json\json.h"
std::string data =FileUtils::getInstance()->getStringFromFile("test.json");
Json::Reader reader;
if (reader.parse(data, root, false)) {
log("%s",root["name"].asCString()); // asCString() 否则乱码
log("%d", root["msg"]["money"].asInt());
log("%d", root["array"][1]["id"].asInt());//数组用 数字 从0开始
}
//写
#include"Classes\json\json.h"
#include <stdio.h>
Json::FastWriter writer;
root["name"] = "Who"; //root有读入内容 这样可以实现更改Json内容 先上面读入root
std::string json_file = writer.write(root);
FILE * file = fopen("test.json", "w"); //“w” 已有的会清空
fprintf(file, json_file.c_str());
fclose(file);
//--------------------------------------------------------------Lua---------------------------------------------------
拷贝文件
D:\cocos2d-x-3.14\external\lua
项目 c++ 附加包含目录
lua\lua
lua\luajit\include
链接器 输入 附加依赖项
lua51.lib
lua51.dll和lua51.lib直接复制到项目的Debug.win32文件夹里面
//lua 是c语言库
extern "C" {
#include <lua.h>
#include<lualib.h>
#include<lauxlib.h>
};
lua_State * pl = lua_open(); //lua 对象
luaopen_base(pl); //加载lua 库
luaopen_math(pl);
luaopen_string(pl);
//执行lua脚步 返回0代表成功
int err = luaL_dofile(pl, "lua/helloLua.lua");
log("open %d", err);
//重置栈顶索引 确认栈顶索引是0 重要
lua_settop(pl, 0);
//取值
//取 myName的值 放入栈中
lua_getglobal(pl, "myName");
//判断栈顶元素是否为string 取值前最好判断下
int isstr = lua_isstring(pl, 1);//栈内 下标1的值 是否是string 0 代表取值失败
log("isstr:%d", isstr);
if (isstr!=0) {
const char * str= lua_tostring(pl, 1);// lua_tocfunction lua_tonumber lua_toboolean
log("get Str =%s", str);
}
lua_pop(pl,1); //清除指定栈数据
lua_close(pl); //释放内存
//取lua table中的值
lua_getglobal(pl, "helloTable"); //table 存入栈
lua_getglobal(pl, "myName");
lua_getglobal(pl, "myName2");
lua_pushstring(pl, "name"); //把"name放入lua栈顶"
lua_gettable(pl, 1); //从栈顶取值 找到table 内对应的值 在放入栈顶 (第二个参数指向table所在的index 1开始)
auto sname = lua_tostring(pl, -1); // 负数索引 取到栈顶的值(刚存入的值)
//调用函数
lua_getglobal(pl, "helloAdd"); //把函数对象 放入栈顶
lua_pushnumber(pl, 10);
lua_pushnumber(pl, 5);
//调用 第二个参数 是 函数参数个数 第三个是 返回参数个数
//从栈顶 开始取依次参数 函数对象 返回值依次压栈(注意顺序)
lua_call(pl, 2, 2);
int iResult = lua_tonumber(pl, -1);
int iResult2 = lua_tonumber(pl, -2);
// lua 调用 cpp 函数
lua_pushnumber(pl, getNumber(num));//把函数返回值压入实现 lua调用 c++函数
二:
cpp
静态函数 static
int HelloWorld::cpp_getNumber(lua_State * pl) {
//从栈中取出元素
int num = (int)lua_tonumber(pl, 1);
//调用getNumber 并压入栈
lua_pushnumber(pl, getNumber(num));
//代表 getnumber 有多少个返回值
return 1;
}
//也是静态函数
int HelloWorld::getNumber(int num) {
return num + num;
}
//dofile 前 注册 函数
lua_register(pl, "cpp_getNumber", cpp_getNumber);
lua文件中
num = cpp_getNumber(1000);
//网络编程