我正在试着让蛇2在颤动。我使用了Timer.periodic()进行游戏循环。我尝试将持续时间指定为1秒。但是Timer.periodic()中的代码在一秒钟内运行多次。我还尝试了调试(尽管我在这方面做得很糟糕),发现Timer.periodic()中的代码运行了多次,却没有跳出它。虽然在调试时,当代码暂停输入时,可能会发生这种情况。但是我不确定.Here是不是我的代码-
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
class SnakePage extends StatefulWidget {
@override
_SnakePageState createState() => _SnakePageState();
}
class _SnakePageState extends State {
int score = 0;
String swipe = '';
bool running = false;
int iterates = 0;
List snake = [
[
[4, 3],
1,
true
],
[
[4, 2],
1,
false
],
[
[4, 1],
1,
false
],
];
// Convert radians to degree
double radians(double degree) {
return ((degree * 180) / pi);
}
void turn(moveEvent) {
double angle = radians(moveEvent.delta.direction);
if (angle >= -45 && angle <= 45) {
this.swipe = 'Swipe Right';
} else if (angle >= 45 && angle <= 135) {
this.swipe = 'Swipe Down';
} else if (angle <= -45 && angle >= -135) {
this.swipe = 'Swipe Up';
} else {
this.swipe = 'Swipe Left';
}
}
int toIndex(coOrdinates) {
return ((coOrdinates[0] + 1) * 10) + coOrdinates[1];
}
void run() {
this.running = true;
Timer.periodic(
Duration(
milliseconds: 500,
), (timer) {
this.setState(() {
this.iterates += 1;
this.swipe = this.iterates.toString();
for (var i = 0; i < this.snake.length; i++) {
this.snake[i][0][1] += 1;
if (this.snake[i][0][1] == 10) {
this.snake[i][0][1] = 0;
}
}
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('WC'),
),
body: Listener(
onPointerMove: this.running
? (moveEvent) => this.turn(moveEvent)
: (moveEvent) => this.run(),// Where the function is being called
child: Container();
);
}
}请原谅我的代码是一团糟,没有很好的评论。任何帮助都将不胜感激!
发布于 2021-02-23 21:52:45
问题是,每次执行run()方法时,将创建一个新的计时器,您将再次侦听该计时器。旧的计时器没有停止,所以它一直在发射。解决方案是,在创建计时器之前,取消前一个计时器。如下所示:
class _SnakePageState extends State {
Timer _myTimer;
void run() {
this.running = true;
_myTimer?.cancel(); //in case we have a timer, we'll cancel it.
_myTimer = Timer.periodic(. // assing new timer to our variable.
Duration(
milliseconds: 500,
), (timer) {
this.setState(() {
this.iterates += 1;
this.swipe = this.iterates.toString();
for (var i = 0; i < this.snake.length; i++) {
this.snake[i][0][1] += 1;
if (this.snake[i][0][1] == 10) {
this.snake[i][0][1] = 0;
}
}
});
});
}
}https://stackoverflow.com/questions/66334289
复制相似问题