四 CocosEditor基础教程第二季 之几个常用的函数

来源:互联网 发布:淘宝罗技百事得专卖店 编辑:程序博客网 时间:2024/04/29 18:46

有些函数曝光率很高,很常用,笔者把他们提出来介绍一下;


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;}



0 0
原创粉丝点击