Flutter 的动画系统可以帮助开发者实现生动的游戏效果,例如物理效果、平移动画、旋转动画等等。以下是一个使用 Flutter 动画系统实现小球弹跳的示例代码:
import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold(body: GameWidget()), )); } class GameWidget extends StatefulWidget { @override _GameWidgetState createState() => _GameWidgetState(); } class _GameWidgetState extends State<GameWidget> with SingleTickerProviderStateMixin { late AnimationController controller; late Animation<double> animation; @override void initState() { super.initState(); controller = AnimationController( duration: const Duration(seconds: 2), vsync: this, )..repeat(reverse: true); animation = Tween<double>(begin: 0, end: 200).animate(controller); } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: animation, builder: (context, child) { return CustomPaint( painter: BallPainter(animation.value), ); }, ); } } class BallPainter extends CustomPainter { final double height; BallPainter(this.height); @override void paint(Canvas canvas, Size size) { final paint = Paint()..color = Colors.blue; final ballSize = 50.0; final ballPosition = Offset(0, size.height - height - ballSize / 2); canvas.drawCircle(ballPosition, ballSize / 2, paint); } @override bool shouldRepaint(covariant CustomPainter oldDelegate) { final oldPainter = oldDelegate as BallPainter; return oldPainter.height != height; } }
以上代码演示了一个通过 Flutter 动画系统实现小球弹跳效果的示例。在该示例中,使用 AnimationController 控制动画时间和方向,并使用 Tween 定义动画范围。在 AnimatedBuilder 中使用 CustomPaint 绘制小球位置。