游戲中經(jīng)常會(huì)遇到需要顯示數(shù)字(比如金錢數(shù)量,戰(zhàn)斗力等等)知给,美術(shù)UI同學(xué)會(huì)給圖片資源,然后我們程序同學(xué)得寫邏輯實(shí)現(xiàn)需求涩赢。
以前做頁游用as3.0也寫過數(shù)字圖片,現(xiàn)在入坑cococs后,好多東西得重新寫一遍帅矗,不過沒關(guān)系。邏輯都是差不多的
下面直接給剛?cè)肟拥男』锇閭兎窒韯偼瓿傻脑创a,我自己測試很多遍了弱睦,性能也做了優(yōu)化,可以直接拿到項(xiàng)目使用屹耐。
const {ccclass, property} = cc._decorator;
/**
* @author Maniac.guo
* Everyone should have a dream 脖捻, what if it came true 羡亩?
* @className 圖片數(shù)字組件
* @data 2018年5月18日
* @mailbox 309506117@qq.com
*/
@ccclass
export class NumberSpriteComponent extends cc.Component {
@property(cc.SpriteAtlas)
sprAtlas:cc.SpriteAtlas = null;
private _poolArr:Array<any> = [];
onLoad() {
}
// public loadTexture( texturePath:string = "res/game/laba_haiyang.png",callBack:Function = null ) :void {
// this._callBack = callBack;
// let self = this;
// if(self._sprAtlas){
// self._callBack();
// }else{
// cc.loader.loadRes(texturePath, cc.SpriteAtlas, function (err, atlas:cc.SpriteAtlas) {
// self._sprAtlas = atlas;
// self._callBack();
// })
// }
// }
public getNodeFromPool( index:number ) : cc.Node {
let numNode:cc.Node = null;
let numSpr:cc.Sprite = null;
if(this._poolArr.length == 0 || (index+1) > this._poolArr.length){
numNode = new cc.Node();
numSpr = numNode.addComponent(cc.Sprite);
this._poolArr.push(numNode);
}
numNode = this._poolArr[index];
if(numNode.parent){
numNode.parent.removeChild(numNode);
}
return numNode;
}
public showNumber( num:number, frameName:string = "num2-" ) : void {
if(this.sprAtlas == null)return;
this.removeReset();
let numArr:string[] = num.toString().split("");
let numNode:cc.Node = null;
let numSpr:cc.Sprite = null;
for(let i:number = 0 ; i < numArr.length ; i++){
numNode = this.getNodeFromPool(i);
this.node.addChild(numNode);
numSpr = numNode.getComponent(cc.Sprite);
let s:string = numArr[i];
numSpr.spriteFrame = this.sprAtlas.getSpriteFrame(frameName+s);
numNode.x = (numSpr.spriteFrame.getRect().width+2)*i;
}
}
private removeReset() : void {
this.node.removeAllChildren();
}
start () {
}
}
如果有不懂的小伙伴可以直接留言贼陶!
附上使用截圖:
直接綁定腳本
顯示效果:
使用邏輯:
let numSprNode:cc.Node = this.node.getChildByName("numSpr");
let sprNode1:cc.Node = numSprNode.getChildByName("num1");
let sprNode2:cc.Node = numSprNode.getChildByName("num2");
let sprNode3:cc.Node = numSprNode.getChildByName("num3");
this.numComponent1 = sprNode1.getComponent(NumberSpriteComponent);
this.numComponent1.showNumber(4569821364);
let numComponent2:NumberSpriteComponent = sprNode2.getComponent(NumberSpriteComponent);
numComponent2.showNumber(253615879);
let numComponent3:NumberSpriteComponent = sprNode3.getComponent(NumberSpriteComponent);
numComponent3.showNumber(78654123);