游戏中经常会遇到需要显示数字(比如金钱数量,战斗力等等),美术UI同学会给图片资源,然后我们程序同学得写逻辑实现需求。
以前做页游用as3.0也写过数字图片,现在入坑cococs后,好多东西得重新写一遍,不过没关系。逻辑都是差不多的
下面直接给刚入坑的小伙伴们分享刚完成的源码,我自己测试很多遍了,性能也做了优化,可以直接拿到项目使用。
const {ccclass, property} = cc._decorator;/*** @author Maniac.guo* Everyone should have a dream , what if it came true ?* @className 图片数字组件* @data 5月18日* @mailbox 309506117@*/@ccclassexport class NumberSpriteComponent extends ponent {@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);