前情提要来自作者上一篇的代码雨
注意为了自然,不要逐帧变化,而是改成每隔N帧变化一次
原理 对每个雨滴做计时管理 ,记录雨滴下落了多少帧,当达到一个帧数时,重新改变文字
更新后的雨滴类
class RainDrop {
double x;
double y;
double speed;
int frameCount = 0;
int frameOffset;
List<String> currentChars = [];
int charUpdateTick = 0;
RainDrop({
required this.x,
required this.y,
required this.speed,
required this.frameOffset,
}){
currentChars = List.generate(10, (_) => _randomChar());
}
String _randomChar() {
const charSet = '我会永远视奸你'; // 你可以换成其他字符集
final r = Random();
return charSet[r.nextInt(charSet.length)];
}
void updateCharsEvery(int n) {
charUpdateTick++;
if (charUpdateTick >= n) {
currentChars = List.generate(10, (_) => _randomChar());
charUpdateTick = 0;
}
}
}
新增属性
- currentChars 来记录当前的雨滴是什么内容 例如012345 变成132450
- charUpdateTick 雨滴多少帧更新一次文本 新增方法
- updateCharsEvery 达到charUpdateTick 更新文本
- _randomChar 随机获取第n个字符 其他变化
RainDrop({
required this.x,
required this.y,
required this.speed,
required this.frameOffset,
}){
currentChars = List.generate(10, (_) => _randomChar());
}
currentChars = List.generate(10, (_) => _randomChar()); 这里是第一次也随机赋值
其他变动
updateCharsEvery 的触发
在雨滴管理器RainManager中update时去触发
void update() {
for (final drop in drops) {
drop.y += drop.speed;
drop.frameCount++;
drop.updateCharsEvery(5);
// 超出屏幕时触发爆散
...
}
// 更新粒子
...
}
文字怎么变化
在RainPainter 雨滴绘制器中
final char = manager.charSet[i % manager.charSet.length];
更改为final char = drop.currentChars[i % drop.currentChars.length];