• Cocos2d-JS开发中的一些小技巧


    1、获取URL中的请求参数的值----此方法接收参数名

    function getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return decodeURIComponent(r[2]);
        return null;
    };
    

    2、底图上添加文字---适用于按钮Sprite

    var MyButtonSprite = cc.Sprite.extend({
        ctor: function (fileName, title, fontName, fontSize) {
            this._super(fileName);
      
            var titleLabel = new cc.LabelTTF(title, fontName, fontSize);
            this.addChild(titleLabel);
            titleLabel.x = this.getContentSize().width / 2;
            titleLabel.y = this.getContentSize().height / 2;
        }
    });
    

    3、远程图片加载

    loadImgFromUrl: function (target, imgUrl, p, tag) {
            if(!imgUrl)return;
            var self = target;
            var loadCb = function(err, img){
                cc.textureCache.addImage(imgUrl);
                var texture2d = new cc.Texture2D();
                texture2d.initWithElement(img);
                texture2d.handleLoadedTexture();
                var sp = new cc.Sprite();
                sp.initWithTexture(texture2d);
                self.addChild(sp);
                sp.x = p.x;
                sp.y = p.y;
                sp.tag = tag;
            };
            cc.loader.loadImg(imgUrl, {isCrossOrigin : false }, loadCb);
        },
    

    4、XMLHttpRequest

    var sendRequest = function(url, params, isPost, callback, errorcallback){
        if(url == null || url == '')
            return;
              
        var xhr = cc.loader.getXMLHttpRequest();
        if(isPost){
            xhr.open("POST",url);
        }else{
            xhr.open("GET",url);
        }
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function () {
            if(xhr.readyState == 4 && xhr.status == 200){
                var response = xhr.responseText;
                if(callback)
                    callback(response);
            }else if(xhr.readyState == 4 && xhr.status != 200){
                var response = xhr.responseText;
                if(errorcallback)
                    errorcallback(response);
            }
        };
      
        if(params == null || params == ""){
            xhr.send();
        }else{
            xhr.send(params);
        }
    };
    

    5、JSON解析以及上述第4条的回调方法

    var callback = function (response) {
            var jsonData = JSON.parse(response);
            var data = jsonData["users"];
            if(data){
                alert(data["name"]);
                // todo something
            }
        };
    

    6、自定义Loading界面

    var MyLoaderScene = cc.Scene.extend({
        _interval : null,
        _length : 0,
        _count : 0,
        _label : null,
        _className:"MyLoaderScene",
        init : function(){
            var self = this;
      
            // bg
            var bgLayer = self._bgLayer = cc.LayerColor.create(cc.color(32, 32, 32, 255));
            bgLayer.setPosition(cc.visibleRect.bottomLeft);
            self.addChild(bgLayer, 0);
      
            //loading percent
            var label = self._label = cc.LabelTTF.create("玩命加载中... 0%", "Arial", 24);
            label.setPosition(cc.pAdd(cc.visibleRect.center, cc.p(0, 0)));
            label.setColor(cc.color(180, 180, 180));
            bgLayer.addChild(this._label, 10);
            return true;
        },
      
        _initStage: function (img, centerPos) {
            var self = this;
            var texture2d = self._texture2d = new cc.Texture2D();
            texture2d.initWithElement(img);
            texture2d.handleLoadedTexture();
            var logo = self._logo = cc.Sprite.create(texture2d);
            logo.setScale(cc.contentScaleFactor());
            logo.x = centerPos.x;
            logo.y = centerPos.y;
            self._bgLayer.addChild(logo, 10);
        },
      
        onEnter: function () {
            var self = this;
            cc.Node.prototype.onEnter.call(self);
            self.schedule(self._startLoading, 0.3);
        },
      
        onExit: function () {
            cc.Node.prototype.onExit.call(this);
            var tmpStr = "玩命加载中... 0%";
            this._label.setString(tmpStr);
        },
      
        /**
         * init with resources
         * @param {Array} resources
         * @param {Function|String} cb
         */
        initWithResources: function (resources, cb) {
            if(typeof resources == "string") resources = [resources];
            this.resources = resources || [];
            this.cb = cb;
        },
      
        _startLoading: function () {
            var self = this;
            self.unschedule(self._startLoading);
            var res = self.resources;
            self._length = res.length;
            self._count = 0;
            cc.loader.load(res, function(result, count){ self._count = count; }, function(){
                if(self.cb)
                    self.cb();
            });
            self.schedule(self._updatePercent);
        },
      
        _updatePercent: function () {
            var self = this;
            var count = self._count;
            var length = self._length;
            var percent = (count / length * 100) | 0;
            percent = Math.min(percent, 100);
            self._label.setString("玩命加载中... " + percent + "%");
            if(count >= length) self.unschedule(self._updatePercent);
        }
    });
    MyLoaderScene.preload = function(resources, cb){
        var _myLoaderScene = null;
        if(!_myLoaderScene) {
            _myLoaderScene = new MyLoaderScene();
            _myLoaderScene.init();
        }
        _myLoaderScene.initWithResources(resources, cb);
      
        cc.director.runScene(_myLoaderScene);
        return _myLoaderScene;
    };
    

    7、网页跳转

    window.location.href = "http://www.baidu.com"

    8、关于进入游戏时黑屏时间较长的处理方法

    1)

    <body style="padding:0; margin: 0; background: #000;">

    删除index.html中<body>标签的样式background: #000;

    2)按照自己需要添加编译模块 修改project.json如

    "modules" : ["core", "actions","shape-nodes", "labels","menus","transitions","physics","chipmunk","gui"],
    

    原文链接:http://cn.cocos2d-x.org/tutorial/show?id=1431

  • 相关阅读:
    微信小程序入门实例
    textarea 的value值以及演示
    Think php (TP5) 批量删除全部源码
    Think php TP5 CURD 增删改查全部源码
    TP5 Think php 批量添加全部源码
    centos7 supervisor管理redis
    Centos7 设置redis开机自启
    Centos7安装gearman和php扩展
    nginx-403
    FFmpeg-截取视频图片
  • 原文地址:https://www.cnblogs.com/recock/p/4106002.html
Copyright © 2020-2023  润新知