要实现弹幕功能,首先需要将弹幕配置成配置表。然后代码随机生成。
/**生成单个弹幕 */ private showCaptionAnim(captionText: string) { egret.log("字幕生成"); var showCaption_1: egret.TextField = new egret.TextField(); showCaption_1.text = captionText; showCaption_1.textColor = 0Xffffff; showCaption_1.size = 40; showCaption_1.x = this.stage.stageWidth - 100; showCaption_1.y = Fight.GameUtil.getRandomInt(this.gameScene.gamePanel.curNPC.y, this.gameScene.gamePanel.y + this.gameScene.gamePanel.curNPC.height / 2) - 50; this.gameScene.gamePanel.captionGroup.visible = true; if (this.gameScene.gamePanel.captionGroup) { this.gameScene.gamePanel.captionGroup.addChild(showCaption_1); // this.gameScene.gamePanel.captionGroup.visible = false; } this.captionMove(showCaption_1); } /**控制单个弹幕的移动 */ private captionMove(text: egret.TextField) { if (text != undefined && text != null) { let random = Math.floor(Math.random() * 10 + 5); egret.Tween.get(text).to({ x: -1300 }, random * 1000).call(() => { egret.Tween.removeTweens(text); }); } } /**随机弹幕 */ private randomCaption() { //取配置表中的所有弹幕,通过/分割成数组 let str = GameData.CfgsData.caption.split("/"); //弹幕概率随机 let num1 = Math.floor(Math.random() * 10);//0-9 //0---true other----false if (num1 == 0) { this.isCaption = true; } else { this.isCaption = false; } if (this.isCaption) { let index = Math.floor(Math.random() * str.length);//随机弹幕数组下标 let currCaption = str[index].toString(); this.showCaptionAnim(currCaption); } }
在需要调用弹幕的时候调用randomCaption函数