creator技巧
1)旋转无锯齿:cc.macro.ENABLE_WEBGL_ANTIALIAS = true;

2)listview使用

    @property(ListView)
    listv: ListView = null;
    private rankListAdapter: RankListAdapter = null;


    initListv() {
        this.rankListAdapter = new RankListAdapter();
        this.listv.setAdapter(this.rankListAdapter);
    }


this.rankListAdapter.setDataSet(data);
this.listv.notifyUpdate(null, false);


class RankListAdapter extends AbsAdapter {
    updateView(item: cc.Node, posIndex: number) {
        let comp = item.getComponent(RankCell);
        if (comp) {
            let data = this.getItem(posIndex);
            comp.setvData(data);
        }
    }
    private time = 0;
    cbScrollTopBottom() {
    }
}

3)creator拷贝文字

    // web copy
    webCopyString(str) {
        var input = str + '';
        const el = document.createElement('textarea');
        el.value = input;
        el.setAttribute('readonly', '');
        el.style.position = 'absolute';
        el.style.left = '-9999px';
        el.style.fontSize = '12pt'; // Prevent zooming on iOS
        const selection = getSelection();
        var originalRange;
        if (selection.rangeCount > 0) {
            originalRange = selection.getRangeAt(0);
        }
        document.body.appendChild(el);
        el.select();
        el.selectionStart = 0;
        el.selectionEnd = input.length;
        var success = false;
        try {
            success = document.execCommand('copy');
        } catch (err) { }
        document.body.removeChild(el);
        if (originalRange) {
            selection.removeAllRanges();
            selection.addRange(originalRange);
        }
        return success;
    }

    // 是否是手机端
    isAndroidApp() {
        if (cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID) {
            return true;
        }
        return false;
    }
    isIosApp() {
        if (cc.sys.isNative && cc.sys.os == cc.sys.OS_IOS) {
            return true;
        }
        return false;
    }

    getDeviceType() {
        return cc.sys.os;
    }
    
    // 设置剪切板数据,复制
    setClipboardData(str) {
        if (G.isAndroidApp()) {
            // jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "setToClipboard", "(Ljava/lang/String;)Ljava/lang/String;", str);
        } else if (G.isIosApp()) {
            // jsb.reflection.callStaticMethod("AppController", "copyToClipboard:stxt:", str, "123");
        } else if (cc.sys.isBrowser) {
            this.webCopyString(str);
        }
    }

4)creator二维码显示

this._Nodes.qrCode.getComponent(QRCodeComponent).setSQrCode('123');

5)JAVA_HOME要配置在系统变量下,不要用用户变量
6)微信头像加载
获取url后,加上?.jpg,即可获得该图片的jpg地址,然后用cc.loader.load加载

var rawData = JSON.parse(res.rawData);
var iconUrl = rawData.avatarUrl;
iconUrl = iconUrl + "?.jpg";
console.log('---iconUrl:', iconUrl);

// 下载玩家头像
cc.loader.load(iconUrl, function(err, texture){
    var sprite = self.userIcon.getComponent(cc.Sprite);
    sprite.spriteFrame = new cc.SpriteFrame(texture);
});

7)ts调用原生函数

//H5
    // data发送到原生
    cccToNature(strData:string){
        if (G.isAndroidApp()) {
            return jsb.reflection.callStaticMethod("org/cocos2dx/javascript/SDKWrapper", "cccToAnd", "(Ljava/lang/String;)Ljava/lang/String;", strData);
        } else if (G.isIosApp()) {
        } else if (cc.sys.isBrowser) {
        }
    }
// android端SDKWrapper.java文件底部加函数
    public static String cccToAnd(String strData){
        System.out.println("println输入日志信息"+strData);
        return  "666";
    }
// android调用ts
    private static AppActivity app = null;
    app = this;
    
    public static void callTsFun(final String strData){
        app.runOnGLThread(new Runnable() {
            @Override
            public void run() {
                Cocos2dxJavascriptJavaBridge.evalString("console.log(\"Javascript Java bridge3!\")");
                String s1 = strData.replace("\n", "");
                String s2 = s1.replace("\"", "\\\"");
                Cocos2dxJavascriptJavaBridge.evalString("natureToccc(\""+s2+"\")");
            }
        });
    }

// H5
window.natureToccc = (strData:string)=>{
    console.log('---H5:',strData);
}

8)creator发布H5资源下载用CDN
修改 main.js 里面的 rawAssetsBase 和 libraryPath 为正确的 url 地址即可。
9)Alt+Enter可以自动引入android studio的库文件。
10)creator打包安卓,混淆闪退问题,打开app/proguard-rules.pro文件加入

-keep class com.quicksdk.** { *; }

11)安卓日志收集,配置adb到环境变量D:\android\sdk\platform-tools,打印日志cmd进入命令

adb logcat -c
adb logcat -v time >.\\logcat.log

这样会收集到crash日志文件啦。
12)打包H5技巧1,creator发布H5会有缓存问题,在index.html里面加入

<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="0">

13)icon自动生成
14)android打包使用版本号:sdk用android-26,Gradle用5.4.1,Gradle Plugin 3.2.0
15)creator模块含义
16)打包小米快游戏 cnpm install -g quickgame-cli
17)vscode搜索排除路径: build-templates,temp,local,build,library,packages
18)creator打包的h5包,会跳一下全屏,修改main.js里面的onStart函数cc.view.enableAutoFullScreen(false);
19)使用protobuf,npm i protobufjs -gproto详细
20)creator预加载

let pnode = await G.getPrefabNodeFromUrl(pname);
pnode.destroy();

21)颜色叠加效果,a+b两张图片,b图片的Dst Blend Factor设置为ONE,就可以了。酷的
22)打包H5技巧2,是否是pc

        function isPC() {
            var userAgentInfo = navigator.userAgent;
            var Agents = ["Android", "iPhone",
                "SymbianOS", "Windows Phone",
                "iPad", "iPod"
            ];
            var flag = true;
            for (var v = 0; v < Agents.length; v++) {
                if (userAgentInfo.indexOf(Agents[v]) > 0) {
                    flag = false;
                    break;
                }
            }
            return flag;
        }

23)打包H5技巧3,移动端适配成pc端,测试加个iframe

  <style>
    #cdiv {
      width: 720px;
      height: 1280px;
      margin: 0 auto;
      /* border: 1px solid; */
    }
  </style>
</head>

<body>
  <div id="cdiv">
    <iframe src="./index.html" style="width: 100%; height: 100%;"></iframe>
  </div>



  <script type="text/javascript">
    function isPC() {
      var userAgentInfo = navigator.userAgent;
      var Agents = ["Android", "iPhone",
        "SymbianOS", "Windows Phone",
        "iPad", "iPod"
      ];
      var flag = true;
      for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
          flag = false;
          break;
        }
      }
      return flag;
    }

    function autopc() {
      if (!isPC()) {
        return;
      }
      let orgHeight = document.documentElement.clientHeight;
      let orgWidth = document.documentElement.clientWidth;
      let newHeight = orgHeight - 20;
      let newWidth = orgWidth;
      console.log('org:', orgHeight, orgWidth);
      if (orgWidth / orgHeight > 0.56) {
        newWidth = orgHeight * 0.56;
      } else {
        newHeight = orgWidth / 0.56;
      }
      document.getElementById('cdiv').style.height = newHeight + 'px';
      document.getElementById('cdiv').style.width = newWidth + 'px';
    }
    autopc();

    window.onresize = function () {
      autopc();
    }
  </script>
</body>

24)导出模板

 module.exports.foo = function () {
      cc.log("foo");
  };
import foo= require("./foo");

25)js字符串拆分str.split(" ")
26)正则验证密码,8到16位数字与字母组合

    checkPassword(str) {
        var pwdReg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/;// 8到16位数字与字母组合
        if (!pwdReg.test(str)) {
            // ('密码校验失败!');
            return false
        } else {
            // ('密码合法!');
            return true;
        }
    }

27)_EditBoxs的Input Flag密码眼睛切换

        if(this.isEyeClose){
            this._EditBoxs.pwd.inputFlag = 0;
        }else{
            this._EditBoxs.pwd.inputFlag = 5;
        }

28)隐藏FPS

cc.debug.setDisplayStats(false);

29)touchstart,touchmove,touchend,touchcancel触摸监听

tnode.on(cc.Node.EventType.TOUCH_START, (touch, event)=> {
    // 返回世界坐标
    let touchLoc = touch.getLocation();
})

        let snode = this._Nodes.slideNode;
        let bnodeend = (lastx) => {
            let dx = lastx - this.touchsnx;
            let newx = this.orgsnx + dx;
            if (newx < this.slideOrgX) {
                newx = this.slideOrgX
            }
            if (newx > -this.slideOrgX) {
                newx = -this.slideOrgX
            }
            snode.x = newx;
            this.onChangeBarTouch(newx);
        }
        snode.x = this.slideOrgX;
        snode.on('touchstart', (touch, event) => {
            let touchLoc = touch.getLocation();
            this.touchsnx = touchLoc.x;
            this.orgsnx = snode.x;
        })
        snode.on('touchmove', (touch, event) => {
            let touchLoc = touch.getLocation();
            bnodeend(touchLoc.x);
        })
        snode.on('touchend', (touch, event) => {
            let touchLoc = touch.getLocation();
            bnodeend(touchLoc.x);
        })
        snode.on('touchcancel', (touch, event) => {
            let touchLoc = touch.getLocation();
            bnodeend(touchLoc.x);
        })

30)安卓使用wss,需要加载证书new WebSocket("wss://echo.websocket.org", [], this.wssCacert.url);,看地址
31)各种超牛逼特性 https://github.com/baiyuwubing/cocos-creator-examples
32)

标签: none

添加新评论