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)js去掉回车换行let str2=str1.replace(/[\r\n]/g,""));//去掉回车换行
33)比较版本号:

    comVersion(a, b) {
        let toNum = function (a) {
            var a = a.toString();
            var c = a.split('.');
            var num_place = ["", "0", "00", "000", "0000"], r = num_place.reverse();
            for (var i = 0; i < c.length; i++) {
                var len = c[i].length;
                c[i] = r[len] + c[i];
            }
            var res = c.join('');
            return res;
        }
        var _a = toNum(a);
        var _b = toNum(b);
        if (_a == _b) cc.log("版本号相同!版本号为:" + a);
        if (_a > _b) cc.log("版本号" + a + "是新版本!");
        if (_a < _b) cc.log("版本号" + b + "是新版本!");
        return _a > _b;
    }

34)按钮1秒内,只点击一下。

    // 播放按钮
    private audiobtnsec = 0;
    playAudioBtn() {
        if (!this.isAudioInSec()) {
            // 同一秒内不播放一样的按钮声音
            return;
        }
        G.playSound(G.AUDIO_ID.AI_BTN);
    }
    isAudioInSec() {
        let curSec = G.getSec();
        if (this.audiobtnsec == 0) {
            this.audiobtnsec = curSec;
            return true;
        }
        if (this.audiobtnsec >= curSec) {
            return false;
        }
        this.audiobtnsec = curSec;
        return true;
    }

35)Label太长,看不到了,要把文本的Cache Mode模式改未CHAR模式,这样才能显示长文本,不然会被截取,看不到了。
36)v2.3+版本屏蔽多点触摸 cc.macro.ENABLE_MULTI_TOUCH = false;
37)ts里set使用,虽然会报红,

let isRepeat = (words)=>{
    let arrWords = words.split(' ');
    let setWords = new Set();
    for (let index = 0; index < arrWords.length; index++) {
        setWords.add(arrWords[index]);
    }
    if(setWords.size == arrWords.length){
        return false;
    }
    return true;
}

38) Editbox遮挡问题

实现效果:如果软键盘挡住了editbox则移动游戏界面到能刚好能看到的位置

思路:
    1.js端获取点击的editbox的世界坐标
    2.调整GLSurfaceView的y坐标

creator版本:2.3.3

1.js端代码
cc.EditBox.prototype._onTouchBegan=function(event){
    let touch=event.touch
    let node=event.target
    let upLoadY=touch.getLocationY()
    let nodePos=node.convertToNodeSpaceAR(touch.getLocation())
    upLoadY-=nodePos.y+node.height/2
    if(cc.sys.isNative){
        if(cc.sys.os==cc.sys.OS_ANDROID){
            jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "upLoadEditBoxY", "(Ljava/lang/String;)V",upLoadY*cc.view.getScaleY())                                
        }else{

        }
    }
}

2. android端代码

Cocos2dxActivity.java
    添加静态变量用于接收js端传递过来的值
    public static float mEditBoxY=0;

    修改软键盘的弹出方式
    window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

Cocos2dxEditBox.java
    修改registKeyboardVisible方法
private void registKeyboardVisible() {
        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                getWindowVisibleDisplayFrame(r);
                int heightDiff = getRootView().getHeight() -(r.bottom-r.top);
                // if more than a quarter of the screen, its probably a keyboard
                if (heightDiff > mScreenHeight/4) {
                    if (!keyboardVisible) {
                        keyboardVisible = true;

                        if(heightDiff>Cocos2dxActivity.mEditBoxY){
                            GLSurfaceView gl=mActivity.getGLSurfaceView();
                            Log.i(TAG, "Cocos2dxActivity.mEditBoxY: "+Cocos2dxActivity.mEditBoxY);
                            float moveY=-(heightDiff-Cocos2dxActivity.mEditBoxY);
                            gl.setY(moveY);
                        }
                    }
                } else {
                    if (keyboardVisible) {
                        keyboardVisible = false;
                        Cocos2dxEditBox.this.hide();
                        GLSurfaceView gl=mActivity.getGLSurfaceView();
                        gl.setY(0);
                    }
                }
            }
        });
    }
    修改Additems方法
    private void addItems(Cocos2dxActivity context, FrameLayout layout) {
        RelativeLayout myLayout = new RelativeLayout(context);
        this.addEditText(context, myLayout);
        this.addButton(context, myLayout);

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        layout.addView(myLayout, layoutParams);
    }

3.隐藏自带的输入框,这里只是调整了下view的添加顺序,让游戏界面挡住了输入框

修改Cocos2dxActivity.java中的ini方法
mEditBox = new Cocos2dxEditBox(this, mFrameLayout);
Cocos2dxRenderer renderer = this.addSurfaceView();

4.在AppActivity.java中添加静态方法
public static void upLoadEditBoxY(String y){
    mEditBoxY=Float.parseFloat(y);
}

39) js替换字符串,只替换第一个:strM.replace("a","A"), 全部替换:strM.replace(/a/g,"A")
40) js精度问题,可以用floor(n+0.00001),js会丢失一点点精度,补一点点给它,这样就无忧了!酷
41)

标签: none

添加新评论