gpt4 book ai didi

flutter 逻辑问题

转载 作者:行者123 更新时间:2023-12-05 05:45:51 25 4
gpt4 key购买 nike

我正在构建这个小游戏,它类似于 Qix 游戏。

我已经构建了第一个屏幕,现在我需要实现该功能,汽车应该使用按钮移动,并且在移动时它应该像一个容器一样在它后面绘制,直到它感觉到整个体育场。

这是我让汽车移动的地方:

class _GameScreenState extends State<GameScreen> {
double xPosition = Random().nextInt(230).toDouble();
double yPposition = Random().nextInt(200).toDouble();
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/bg.png"),
fit: BoxFit.cover,
),
),
child: Column(
children: [
// Game play
Expanded(
flex: 6,
child: Stack(
children: [
Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
color: Colors.transparent,
),
Positioned(
bottom: yPposition,
left: xPosition,
child: Image.asset("assets/images/car.png"),
)
],
),
),
// Player inputes
Expanded(
child: Container(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
RoundIconButton(
onPress: () {
setState(() {
yPposition--;
});
},
icon: Icons.arrow_downward,
),
RoundIconButton(
onPress: () {
setState(() {
yPposition++;
});
},
icon: Icons.arrow_upward,
),
],
),
Row(
children: [
RoundIconButton(
onPress: () {
setState(() {
xPosition--;
});
},
icon: Icons.arrow_back,
),
RoundIconButton(
onPress: () {
setState(() {
xPosition = xPosition + 10;
});
},
icon: Icons.arrow_forward,
),
],
),
],
),
),
),
),
],
),
),
),
);
}
}

我还需要当我按下按钮时汽车继续移动,在我的例子中它只移动一次

最佳答案

您可以设置一个计时器,您希望多久更改一次位置。

要获取点击事件,GestureDetector 适用于这种情况,我们将使用 onPanStart 更新使用计时器的值,并使用 onPanEnd 取消计时器。

dartPad 上运行.

  late Timer timer;

final duration = const Duration(milliseconds: 100);
void moveUp(_) {
timer = Timer.periodic(duration, (timer) {
setState(() {
yPposition++;
});
});
}

void moveDown(_) {
timer = Timer.periodic(duration, (timer) {
setState(() {
yPposition--;
});
});
}

void moveRight(_) {
timer = Timer.periodic(duration, (timer) {
setState(() {
xPosition++;
});
});
}

void moveLeft(_) {
timer = Timer.periodic(duration, (timer) {
setState(() {
xPosition--;
});
});
}

void onEnd(_) {
timer.cancel();
}

会用到的方法

Row(
children: [
GestureDetector(
onPanStart: moveDown,
onPanEnd: onEnd,
child: Icon(Icons.arrow_downward),
),
GestureDetector(
onPanStart: moveUp,
onPanEnd: onEnd,
child: Icon(Icons.arrow_upward),
),
],
),
Row(
children: [
GestureDetector(
onPanStart: moveRight,
onPanEnd: onEnd,
child: Icon(Icons.arrow_forward),
),
GestureDetector(
onPanStart: moveLeft,
onPanEnd: onEnd,
child: Icon(Icons.arrow_back),
),
],
),
],
),

关于 flutter 逻辑问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71276472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com