dependencies:
flame: ^1.2.0
flame_audio: ^1.2.0
.
.
.
flutter:
assets:
- assets/audio/ball.wav
import 'dart:async';
import 'package:flame/flame.dart';
import 'package:flame/game.dart';
import 'package:flame/components.dart';
import 'package:flame_audio/flame_audio.dart';
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Flame.device.setPortrait();
final shapeGame = ShapesExample();
runApp(GameWidget(game: shapeGame));
}
class ShapesExample extends FlameGame {
@override
Future<void> onLoad() async {
super.onLoad();
add(RectComponent(size[0], size[1]));
}
// @override
// void update(double dt) {
// super.update(dt);
// }
// @override
// void render(Canvas canvas) {
// super.render(canvas);
// }
}
// Add a [Color] Rect on screen
class RectComponent extends Component {
double screenWidthMax = 0;
double screenHeightMax = 0;
double xStartPosition = 0;
double yStartPosition = 0;
static double xRectWidth = 50;
static double yRectHeight = 50;
bool xDirection = true;
final paint = Paint()
..color = Colors.white
..strokeWidth = 4;
RectComponent(this.screenWidthMax, this.screenHeightMax);
@override
Future<void> onLoad() async {
super.onLoad();
// Set the start position of the Rect - center of the screen
xStartPosition = (screenWidthMax) / 2;
yStartPosition = (screenHeightMax) / 2;
// Load and cache the audio
await FlameAudio.audioCache.load('ball.wav');
}
@override
void update(double dt) {
super.update(dt);
if (xDirection == true) {
xStartPosition += 5;
if (xStartPosition >= (screenWidthMax - xRectWidth)) {
xDirection = false;
FlameAudio.play('ball.wav');
}
}
if (xDirection == false) {
xStartPosition -= 5;
if (xStartPosition <= (0)) {
xDirection = true;
FlameAudio.play('ball.wav');
}
}
}
@override
void render(Canvas canvas) {
super.render(canvas);
canvas.drawRect(
Rect.fromLTWH(
xStartPosition,
yStartPosition,
xRectWidth,
yRectHeight),
paint);
}
}
add link to audio file