当前位置 : 主页 > 手机开发 > 其它 >

cocos creator动态更换纹理

来源:互联网 收集:自由互联 发布时间:2021-06-13
有2种办法。 1 是预先准备好所有的纹理,然后放到编辑器中,绑定到对应的脚本。 替换的时候只需要将目标的spriteFrame=source.spriteFrame即可。 把图片拖到编辑器中 创建一个数组,创建当

有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种办法不需要预先把图片放到编辑器中,刚刚的代码里面已经贴出来了如何实现,这种办法更灵活。推荐使用。

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

网友评论