【发布时间】:2021-02-23 13:42:25
【问题描述】:
我正在尝试让蛇 2 颤动。我已经使用 Timer.periodic() 进行游戏循环。我尝试将持续时间指定为 1 秒。但是 Timer.periodic() 中的代码在一秒钟内运行多次。我也尝试过调试(虽然我很糟糕),发现 Timer.periodic() 中的代码运行了多次而没有退出。尽管在调试时,这可能会在代码暂停输入时发生。但我不确定。这是我的代码 -
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
class SnakePage extends StatefulWidget {
@override
_SnakePageState createState() => _SnakePageState();
}
class _SnakePageState extends State<SnakePage> {
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();
);
}
}
请原谅我的代码是一团糟,没有很好的评论。 任何帮助将不胜感激!
【问题讨论】:
标签: flutter dart mobile-development