Created
July 23, 2020 12:52
-
-
Save sthefanoss/ca54535ca991edbea0b03be4af31e2bd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) => MaterialApp(home: MyHomePage()); | |
} | |
class MyHomePage extends StatefulWidget { | |
@override | |
_MyHomePageState createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> | |
with SingleTickerProviderStateMixin { | |
Offset position = Offset(20, 20); | |
Velocity velocity = Velocity.zero; | |
bool _simulating = true; | |
double _friction = 1000; | |
double _time = 0; | |
double _dt = 0; | |
@override | |
void initState() { | |
this.createTicker((elapsed) { | |
if (_simulating) { | |
setState( | |
() { | |
//delta time calculation | |
double _newTime = elapsed.inMicroseconds / 1e6; | |
_dt = _newTime - _time; | |
_time = _newTime; | |
//euler integration | |
if (velocity.pixelsPerSecond.distance < 10) return; | |
velocity = Velocity( | |
pixelsPerSecond: velocity.pixelsPerSecond - | |
velocity.pixelsPerSecond * | |
(_dt * _friction / velocity.pixelsPerSecond.distance), | |
); | |
position = position + velocity.pixelsPerSecond * _dt; | |
}, | |
); | |
} | |
}).start(); | |
super.initState(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text('${(1 / _dt).toStringAsFixed(1)} fps'), | |
), | |
body: LayoutBuilder( | |
builder: (context, constraints) { | |
return GestureDetector( | |
onPanStart: (DragStartDetails details) { | |
position = details.localPosition; | |
velocity = Velocity.zero; | |
}, | |
onPanUpdate: (DragUpdateDetails details) { | |
position = details.localPosition; | |
velocity = Velocity.zero; | |
}, | |
onPanEnd: (DragEndDetails details) { | |
velocity = details.velocity; | |
}, | |
child: CustomPaint( | |
painter: ShapePainter(position), | |
child: Container( | |
height: constraints.maxHeight, | |
width: constraints.maxWidth, | |
), | |
), // This trailing comma makes auto-formatting nicer for build methods. | |
); | |
}, | |
), | |
); | |
} | |
} | |
class ShapePainter extends CustomPainter { | |
final Offset position; | |
const ShapePainter(this.position); | |
@override | |
void paint(Canvas canvas, Size size) { | |
canvas.drawRect(Rect.fromCircle(radius: 25, center: position), | |
Paint()..color = Colors.pink); | |
} | |
@override | |
bool shouldRepaint(CustomPainter oldDelegate) { | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment