Last active
February 13, 2021 15:38
-
-
Save sooxt98/5c382c3db17936ead88c34bafd582672 to your computer and use it in GitHub Desktop.
flame example
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 'dart:math' as math; | |
import 'dart:ui'; | |
import 'package:flame/components.dart'; | |
import 'package:flame/game.dart'; | |
import 'package:flame/gestures.dart'; | |
import 'package:flame/palette.dart'; | |
import 'package:flutter/material.dart'; | |
import 'package:flame/extensions.dart'; | |
void main() { | |
runApp( | |
GameWidget( | |
game: MyGame(), | |
), | |
); | |
} | |
class Palette { | |
static const PaletteEntry white = BasicPalette.white; | |
static const PaletteEntry red = PaletteEntry(Color(0xFFFF0000)); | |
static const PaletteEntry blue = PaletteEntry(Color(0xFF0000FF)); | |
} | |
class Square extends PositionComponent with HasGameRef<MyGame> { | |
Square() { | |
size = Vector2.all(128); | |
anchor = Anchor.center; | |
} | |
static const SPEED = 0.25; | |
static Paint white = Palette.white.paint; | |
static Paint red = Palette.red.paint; | |
static Paint blue = Palette.blue.paint; | |
@override | |
void render(Canvas c) { | |
super.render(c); | |
c.drawRect(size.toRect(), white); | |
c.drawRect(const Rect.fromLTWH(0, 0, 3, 3), red); | |
c.drawRect(Rect.fromLTWH(width / 2, height / 2, 3, 3), blue); | |
} | |
// @override | |
// void update(double t) { | |
// super.update(t); | |
// angle += SPEED * t; | |
// angle %= 2 * math.pi; | |
// // print(angle); | |
// } | |
@override | |
void onMount() { | |
super.onMount(); | |
// print(gameRef.squareSize); | |
} | |
} | |
class MyComponent extends PositionComponent with Tapable, HasGameRef<MyGame> { | |
double speed = 100; | |
Vector2 tappedPoint; | |
MyComponent() { | |
this.addChild( | |
Square() | |
..x = 100 | |
..y = 100, | |
gameRef: gameRef); | |
} | |
@override | |
void update(double dt) { | |
super.update(dt); | |
if (tappedPoint != null && tappedPoint.distanceTo(position) > 10) { | |
angle += position.angleToSigned(tappedPoint); | |
print(angle); | |
final direction = (tappedPoint - position).normalized(); | |
position.add(direction * (dt * speed)); | |
} | |
} | |
@override | |
bool onTapDown(TapDownDetails details) { | |
tappedPoint = details.localPosition | |
.toVector2(); // Import the Offset extension to access toVector2 | |
return true; | |
} | |
} | |
class MyGame extends BaseGame with HasTapableComponents { | |
final double squareSize = 128; | |
bool running = true; | |
MyGame() { | |
add(MyComponent()); | |
// add(Square() | |
// ..x = 100 | |
// ..y = 100); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment