
点击上方蓝色字关注我们~
给游戏添加弹幕应该算是一种比较新鲜的想法。开发人员可以在弹幕中添加一些游戏玩法提示,这样可以一定程度上简化新手引导步骤。当然,弹幕也可以增加游戏的趣味性。现在让我们来看下如何实现弹幕功能。
运行效果如下:

Cocos Creator版本:2.2.2
后台回复"弹幕",获取该项目完整文件。
创建节点
首先我们在层级管理器中添加如下节点:

bg为Sprite类型节点,颜色为白色,作为背景。
Bullet Screen用来添加弹幕文本,注意弹幕不是加到Canvas上。
bullet为弹幕预制,类型为Label,注意要将锚点x设为0。
编写脚本
在资源管理器中创建一个名为BulletScreen.js的脚本文件,挂到Bullue Screen节点上。
我们首先在该脚本的最开头定义要显示的弹幕:
// BulletScreen.jsconst Bullets = ['这是一条没有感情的弹幕', '这还是一条没有感情的弹幕', '666666', '1+1=2', '游戏弹幕可以增加游戏趣味性', 'la vie est belle', 'Hello, World!', '谢谢大家支持!', '也可以放上一些游戏玩法提示', '啦啦啦', 'emmmmm....', '2+2=4', '希望Cocos越来越棒!'];
接着在properties中添加一个预制属性:
// BulletScreen.jsproperties: { bulletPrefab: cc.Prefab},
onLoad方法如下:
// BulletScreen.jsonLoad () { // 确保在不同机型下该节点都与屏幕大小一致 this.node.width = cc.Canvas.instance.node.width; this.node.height = cc.Canvas.instance.node.height; // 当前出现在屏幕上的弹幕数组 this.bulletsArray = [];},
最主要的方法是spawnBullets:
// BulletScreen.jsspawnBullets () { // 生成提示文本 let num = Math.round(Math.random()*4); // 决定生成的数量 for (let i=0; i let bullet = cc.instantiate(this.bulletPrefab); this.bulletsArray.push(bullet); this.node.addChild(bullet); bullet.x = this.node.width/2; bullet.getComponent(cc.Label).string = this.randomContent(); bullet.color = this.randomColor(); bullet.speed = this.randomSpeed(); bullet.y = this.randomStartPosY(); }},
在该方法中我们决定了每次生成的弹幕数量、内容、颜色、速度以及生成位置。
各个随机方法编写如下:
// BulletScreen.jsrandomColor () { // 文本颜色随机 let red = Math.round(Math.random()*255); let green = Math.round(Math.random()*255); let blue = Math.round(Math.random()*255); return new cc.Color(red, green, blue);}, randomContent () { // 文本内容随机 let index = Math.round(Math.random()*(Bullets.length-1)); let bullet = Bullets[index]; return bullet;}, randomSpeed () { // 移动速度随机 let speed = Math.round(Math.random()*100) + 50; return speed;}, randomStartPosY () { // 初始y坐标随机 let height = this.node.height; let y = Math.round(Math.random()*height*0.8) - height*0.4; return y;},
最后我们在update中调用spawnBulluts方法生成弹幕,并将已经显示完的弹幕销毁:
// BulletScreen.jsupdate (dt) { let record = []; for (let i=0; i<this.bulletsArray.length; i++) { this.bulletsArray[i].x -= dt*this.bulletsArray[i].speed; // 文本完全移动到屏幕左侧后,回收 if (this.bulletsArray[i].x <= -(this.node.width/2 + this.bulletsArray[i].width)) { this.bulletsArray[i].removeFromParent(); record.push(i); } } // 删除已完成移动的文本元素 for (let i=0; i this.bulletsArray.splice(record[i], 1); } // 当前所有提示文本消失后,重新生成 if (this.bulletsArray.length == 0) { let trigger = Math.random(); if (trigger>0.99) {this.spawnBullets();} }},
就这么简单,希望大家有所收获。