Skip to content

Latest commit

 

History

History
128 lines (96 loc) · 2.31 KB

ex17-6.md

File metadata and controls

128 lines (96 loc) · 2.31 KB

17.6 Adding sound effects to a Flame Game

Example: dependencies

dependencies:
  flame: ^1.2.0
  flame_audio: ^1.2.0
.
.
.
flutter:
  assets:
    - assets/audio/ball.wav

Example: code

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