Skip to content

Latest commit

 

History

History
76 lines (61 loc) · 1.51 KB

ex17-3.md

File metadata and controls

76 lines (61 loc) · 1.51 KB

17.3 Refactoring with Flame components

Example

import 'dart:async';
import 'package:flame/flame.dart';
import 'package:flame/game.dart';
import 'package:flame/components.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 {
  final double screenWidth;
  final double screenHeight;
  double xStartPosition = 0;
  double yStartPosition = 0;
  static double xRectWidth = 50;
  static double yRectHeight = 50;

  final paint = Paint()
    ..color = Colors.white
    ..strokeWidth = 4;

  RectComponent(this.screenWidth, this.screenHeight);

  @override
  void update(double dt) {
    super.update(dt);
    xStartPosition = screenWidth / 2;
    yStartPosition = screenHeight / 2;
  }

  @override
  void render(Canvas canvas) {
    super.render(canvas);

    // xStartPos, yStartPos, xRectWidth, yRectHeight
    canvas.drawRect(
        Rect.fromLTWH(
          xStartPosition,
          yStartPosition,
          xRectWidth,
          yRectHeight),
        paint);
  }
}