1.巧用单例模式存储数据,很方便。
存储一些数据啊,什么的。场景切换之后使用很方便
//-1.1单例对象
var LibData = cc.Class({
ctor () {
this.coin = 66666;
},
statics: {
_instance: null
},
properties: {
},
setCoin:function(coin)
{
this.coin = coin;
},
getCoin:function()
{
return this.coin;
},
});
LibData._instance = new LibData();
module.exports = LibData;
//-1.2在组件中调用
var LibData = require("LibData")._instance;
cc.Class({
extends: cc.Component,
properties: {
},
// LIFE-CYCLE CALLBACKS:
onLoad :function() {
LibData.setCoin(6666);
},
start () {
},
// update (dt) {},
});
2.如果使用websocket,一定要有断网重连和心跳。
不然莫名其妙断线,连不上的。
- 每次收到服务端消息,重置心跳定时器。
- 收到服务端消息超时
- 收到断开消息重连
- 重新连接加个1秒定时器。
3.个人把网络相关封装到单例里,
每个场景设置一个回调函数,根据不同的消息类型在进行分发
var LibNet = cc.Class({
ctor () {
this.init_config();
},
init_config:function()
{
this.token = "e733d6ac0d1cfd11ecad01047bfa22d0938d6e77";
this.ip ="127.0.0.1:8000";
this.URL= "http://"+this.ip+"/";
this.websocket= "ws://"+this.ip+"/ws/";
},
statics: {
_instance: null
},
properties: {
},
setToken:function(str)
{
this.token = str;
},
connect:function()
{
};
reconnect:function()
{
},
....
}
LibNet._instance = new LibNet();
module.exports = LibNet;
4.通用的listview,也就是排行榜那个效果
我们需要做通用
例如:
ItemMail.js list单条结果,主要负责一些点击事件
maillist.js list组件,负责维护list数据的增删查改
点击单条有网络处理,
我都会让其交给场景类处理,所有的网络请求相关全部交给主场景处理
AniMgr.js 负责动画
AudioMgr.js 负责音效
找到常驻节点
this.Audio = cc.find(“AudioMgr”).getComponent(“AudioMgr”);
添加音效组件为常驻节点
cc.game.addPersistRootNode(this.node);
6.巧用数组来解决来访问组件
cc.Class({
extends: cc.Component,
properties: {
arryBox:[cc.Node],
Box:cc.Node, //行走的灯
LayerBox:cc.Node,//所有灯的位置
},
init:function()
{
cc.log("AniMgr init");
var childrenBox = this.LayerBox.children;
for(var j = 0; j<childrenBox.length; ++j)
{
this.arryBox.push(childrenBox[j]);
}
this.arryBox[this.currentBox].active = true;
},
onLoad:function()
{
if(AudioSwitch)
{
this.Audio = cc.find("AudioMgr").getComponent("AudioMgr");
}
},
start () {
},
// update (dt) {},
});
7.介绍一下我写的练手项目吧
客户端:cocos creater
通信:http/websocket
数据库:mysql,redis
服务端:python3(django,drf,channel,simpleui)
部署:宝塔(mysql,redis,nginx,daphne,asgi)
附图几张:



