Implement a Joystick in Flutter and Flame

The class hud:

lib\components\hud\hud.dart

import 'dart:async';

import 'package:flame/components.dart';
import 'package:flame/palette.dart';
import 'package:flutter/widgets.dart';
import 'package:parallax06/hud/joystick.dart';

class HudComponent extends PositionComponent {
  late Joystick joystick;

  @override
  void onLoad() {
    final joystickKnobPaint = BasicPalette.red.withAlpha(200).paint();
    final joystickBackgroundPaint = BasicPalette.black.withAlpha(100).paint();

    joystick = Joystick(
        knob: CircleComponent(radius: 30.0, paint: joystickKnobPaint),
        background:
            CircleComponent(radius: 100, paint: joystickBackgroundPaint),
        margin: const EdgeInsets.only(left: 40, top: 100));

    add(joystick);
  }
}

With the following implementation, you can scroll a player using the scroll

class PlayerComponent extends Character with HasGameRef<MyGame> {
  ***
  final double _maxVelocity = 5.0;

  @override
  void update(double dt) {
    ***
    _movePlayerJoystick(dt);
  }

  void _movePlayerJoystick(double delta) {
    if (gameRef.hudComponent.joystick.direction != JoystickDirection.idle) {
      position.add(gameRef.hudComponent.joystick.delta * _maxVelocity * delta);
    }
  }
} 

- Andrés Cruz

En español
Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.