有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
這個網站解決了大家開始設計階段的問題,輕量級的各種設計模型,強烈推薦。