cocos creator动态更换纹理

有2种办法。
1 是预先准备好所有的纹理,然后放到编辑器中,绑定到对应的脚本。
替换的时候只需要将目标的spriteFrame=source.spriteFrame即可。

把图片拖到编辑器中
这里写图片描述
创建一个数组,创建当前的要替换纹理索引

 imgIdx : 1,
 sprArray :{
            default:[],
            type:[cc.Sprite],
        },

把编辑器中的图片与数组绑定
这里写图片描述

在编辑器中增加2个按钮,一个减,一个加,当是减的时候向前变,加的时候向后变,把按钮的click事件绑定到脚本中。
添加如下代码

 clickBtn:function(event){
        if(event.target == this.btnl.node){
            this.imgIdx =  --this.imgIdx < 1 ? 5 : this.imgIdx
        }
        else if(event.target == this.btnr.node){
            this.imgIdx = this.imgIdx++ % 5 + 1
        }
        // 方法1
        this.spr.spriteFrame = this.sprArray[this.imgIdx-1].spriteFrame
        // 方法2
        // var s = "resources/candy_0" + this.imgIdx + ".png"
        // this.spr.spriteFrame = new cc.SpriteFrame(cc.url.raw(s))
    }

第2种办法不需要预先把图片放到编辑器中,刚刚的代码里面已经贴出来了如何实现,这种办法更灵活。推荐使用。
第2种方法有个问题就是必须把资源放到resources目录下面,不然到不到。

https://www.processon.com/i/568c6ea4e4b0e51d149a085f
这个网站解决了大家开始设计阶段的问题,轻量级的各种设计模型,强烈推荐。

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