四 CocosEditor基礎教程第二季 之幾個常用的函數

有些函數曝光率很高,很常用,筆者把他們提出來介紹一下;


plist圖片緩存

如果ccbx裏面用到了某個plist的圖片,這個plist會自動添加到緩存,而如果ccbx裏面沒用到plist,而代碼需要用到某個圖片的時候,就需要加入緩存

cc.SpriteFrameCache.getInstance().addSpriteFrames("res/snow_packer.plist");

精靈圖片

1  如果圖片在res下面,沒有打包texture;

創建

cc.Sprite.create("res/whiteBlock.png")

更換

sprite.init("res/whiteBlock.png")


2 如果圖片已經打包在texturepacker裏面;

創建

cc.Sprite.createWithSpriteFrameName("whiteBlock.png")

更換

sprite.initWithSpriteFrameName("whiteBlock.png")


獲取精靈寬高

getBoundingBox是獲取精靈矩形,也很常用

var width = sprite.getBoundingBox().width;
var height = sprite.getBoundingBox().height;


屏幕寬高

var winSize = cc.Director.getInstance().getWinSize();
 this.Width = winSize.width;
 this.Height = winSize.height;


update函數

dt默認是1/60也就每秒刷新60次,相當於0.167秒刷新一次,如果schedule第二個參數沒寫,默認是dt=1/60

當然也可以指定間隔,比如第二個就是每5秒刷新一次;

this.rootNode.schedule(function (dt) {
        this.controller.onUpdate(dt);
    });

this.rootNode.schedule(function (dt) {
        this.controller.onUpdate(dt);
    }, 5);



延遲函數

如果function包含了this,爲了避免function的this和外面的this混淆,所以外面定義that=this;如下面延遲5秒執行,如果沒有this,都可以直接調用

    var that = this;
    this.rootNode.scheduleOnce(function () {
        that.goStart();
        cc.Toast.create(that.rootNode, "hi", 1);
        cc.AudioEngine.getInstance().stopMusic(true);
    }, 5);



回調函數CallFunc

出現this也要用that代替

 var that = this;
this.playSprite.runAction(cc.Sequence.create(cc.ScaleTo.create(0.1, 1.1),
            cc.CallFunc.create(function () {
                cc.Toast.create(that.rootNode, "我是sprite button", 1);
            })
        ));

隨機函數

從一個最大值取一個隨機數

function getRandom(maxSize) {
    return Math.floor(Math.random() * maxSize) % maxSize;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章