1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > cocos creator 绘制闪电特效

cocos creator 绘制闪电特效

时间:2023-08-25 13:53:12

相关推荐

cocos creator 绘制闪电特效

核心算法来自这篇帖子,建议先看看原帖:

【Cocos2d-x教程(20)-闪电效果】/u012945598/article/details/18862091

看懂的大佬可以直接走了~ 下面将原算法改写成cocos creator可用的代码。

首先新建个节点用来绘制闪电。该节点添加组件:渲染组件-Graphics。

Graphics组件可以用来绘制线段,但同时只能绘制一种宽度、颜色、类型的线段;当然可以在代码里动态设置来绘制不同参数的线段。不过,可以在外面直接设好LineWidth(线宽度)和StrokeColor(线颜色),这些会直接应用到闪电上。

接着往该节点上添加自己的脚本。当然脚本添加在其他节点上也行,修改一下获取组件的方式。代码如下:

onLoad() {this.draw = this.node.getComponent(cc.Graphics); // 获取本节点的Graphics组件this.curDetail = 30; // 这个参数影响闪电每一段的长度,值越小,闪电越细腻},// 画一条线段。线段的宽度、颜色等参数在外面Graphics面板设置好了。drawLine(x1, y1, x2, y2) {this.draw.moveTo(x1, y1); // 设置路径起点this.draw.lineTo(x2, y2); // 终点this.draw.stroke(); // 填充路径},// 画一条闪电。闪电由多条线段组成。参数displace影响闪电的剧烈程度,值越大越剧烈。drawLighting(x1, y1, x2, y2, displace) {if (displace < this.curDetail) {this.drawLine(x1, y1, x2, y2);} else {let mid_x = (x1 + x2) / 2;let mid_y = (y1 + y2) / 2;mid_x += (Math.random() - 0.5) * displace;mid_y += (Math.random() - 0.5) * displace;this.drawLighting(x1, y1, mid_x, mid_y, displace / 2);this.drawLighting(x2, y2, mid_x, mid_y, displace / 2);}},// 每帧刷新update(dt) {// 先清空Graphics已绘制的所有东西,不然会和上一帧的叠加在一起。this.draw.clear();// 画个闪电this.drawLighting(-250, -150, 250, 150, 250);// 如果觉得不过瘾,可以每帧多调用几次drawLighting,多生成几条闪电。},

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。