Last active
June 20, 2022 17:59
-
-
Save spydon/333abe1946325ead70dd0070498cce7e to your computer and use it in GitHub Desktop.
Colored towers
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:flame/components.dart'; | |
import 'package:flame/extensions.dart'; | |
import 'package:flame/game.dart'; | |
import 'package:flame/input.dart'; | |
import 'package:flame/effects.dart'; | |
import 'package:flutter/material.dart'; | |
void main() { | |
runApp( | |
GameWidget(game: TowerGame()), | |
); | |
} | |
double edgeLength = 50.0; | |
class TowerGame extends FlameGame with HasHoverables, TapDetector { | |
@override | |
Future<void> onLoad() async { | |
final xCount = (size.x / edgeLength).ceil(); | |
final yCount = (size.y / edgeLength).ceil(); | |
final color = ColorExtension.random(); | |
for (var x = 0; x < xCount; x++) { | |
for (var y = 0; y < yCount; y++) { | |
add(TowerComponent( | |
position: | |
Vector2(x * edgeLength, y * edgeLength) - Vector2.all(edgeLength), | |
paint: Paint() | |
..color = color.brighten((x + y + 0.001) / (xCount + yCount)), | |
priority: -(x + y), | |
)); | |
} | |
} | |
} | |
@override | |
void onTap() { | |
children.query<TowerComponent>().forEach((c) => c.sink(delay: c.priority * -1 / 50)); | |
} | |
} | |
class TowerComponent extends PositionComponent with Hoverable { | |
TowerComponent( | |
{required super.position, required Paint paint, required super.priority}) | |
: super( | |
children: [ | |
RectangleComponent( | |
position: startPosition.clone(), | |
size: Vector2.all(edgeLength), | |
paint: paint, | |
), | |
PolygonComponent( | |
[ | |
startPosition.clone(), | |
startPosition.clone()..x += edgeLength, | |
Vector2( | |
startPosition.x - edgeLength, startPosition.y - edgeLength), | |
], | |
paint: Paint()..color = Colors.white.darken(0.1), | |
), | |
PolygonComponent( | |
[ | |
startPosition.clone(), | |
startPosition - Vector2.all(edgeLength), | |
startPosition.clone()..y += edgeLength, | |
], | |
paint: Paint()..color = Colors.white.darken(0.3), | |
), | |
], | |
size: Vector2.all(edgeLength * 2), | |
) { | |
sink(delay: priority * -1 / 100); | |
} | |
static Vector2 startPosition = Vector2(0, edgeLength); | |
@override | |
bool onHoverEnter(PointerHoverInfo info) { | |
sink(); | |
return false; | |
} | |
void sink({double delay = 0}) { | |
add( | |
ScaleEffect.to( | |
Vector2.all(0.8), | |
EffectController( | |
duration: 1.0, | |
curve: Curves.decelerate, | |
alternate: true, | |
startDelay: delay, | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment