virtual_joystick.dart 1.76 KB
Newer Older
1
part of flutter_sprites;
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

class VirtualJoystick extends NodeWithSize {
  VirtualJoystick() : super(new Size(160.0, 160.0)) {
    userInteractionEnabled = true;
    handleMultiplePointers = false;
    position = new Point(160.0, -20.0);
    pivot = new Point(0.5, 1.0);
    _center = new Point(size.width / 2.0, size.height / 2.0);
    _handlePos = _center;

    _paintHandle = new Paint()
      ..color=new Color(0xffffffff);
    _paintControl = new Paint()
      ..color=new Color(0xffffffff)
      ..strokeWidth = 1.0
17
      ..style = ui.PaintingStyle.stroke;
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
  }

  Point _value = Point.origin;
  Point get value => _value;

  bool _isDown = false;
  bool get isDown => _isDown;

  Point _pointerDownAt;
  Point _center;
  Point _handlePos;

  Paint _paintHandle;
  Paint _paintControl;

  bool handleEvent(SpriteBoxEvent event) {
34
    if (event.type == PointerDownEvent) {
35 36 37 38
      _pointerDownAt = event.boxPosition;
      actions.stopAll();
      _isDown = true;
    }
39
    else if (event.type == PointerUpEvent || event.type == PointerCancelEvent) {
40 41
      _pointerDownAt = null;
      _value = Point.origin;
Hixie's avatar
Hixie committed
42
      ActionTween moveToCenter = new ActionTween((a) => _handlePos = a, _handlePos, _center, 0.4, Curves.elasticOut);
43 44
      actions.run(moveToCenter);
      _isDown = false;
45
    } else if (event.type == PointerMoveEvent) {
46 47 48 49 50 51 52 53 54 55 56
      Offset movedDist = event.boxPosition - _pointerDownAt;

      _value = new Point(
        (movedDist.dx / 80.0).clamp(-1.0, 1.0),
        (movedDist.dy / 80.0).clamp(-1.0, 1.0));

        _handlePos = _center + new Offset(_value.x * 40.0, _value.y * 40.0);
    }
    return true;
  }

Adam Barth's avatar
Adam Barth committed
57
  void paint(Canvas canvas) {
58 59 60 61 62
    applyTransformForPivot(canvas);
    canvas.drawCircle(_handlePos, 25.0, _paintHandle);
    canvas.drawCircle(_center, 40.0, _paintControl);
  }
}