Skip to the content.

슈팅게임 만들기 #4

학습목표

구현

Button class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
typedef NotificationCallback = void Function();

const BUTTON_SIZE = 60.0;
const BUTTON_POSITION_LEFT = -1;
const BUTTON_POSITION_RIGHT = 1;

class Button extends GameControl {
  final NotificationCallback onDown;
  final NotificationCallback onUp;
  final int direction;

  Button({required this.onDown, required this.onUp, required this.direction});

  @override
  void onStart(Canvas canvas, Size size, int current) {
    y = size.height - BUTTON_SIZE * 2;
    width = BUTTON_SIZE ;
    height = BUTTON_SIZE;
    paint.color = Colors.grey.withOpacity(0.1);

    const BUTTON_MARGIN = 20.0;
    switch(direction) {
      case BUTTON_POSITION_LEFT:
        x = BUTTON_MARGIN;
        break;
      case BUTTON_POSITION_RIGHT:
        x = size.width - width - BUTTON_MARGIN;
        break;
    }
  }

  @override
  void onHorizontalDragStart(DragStartDetails details) {
    onDown();
  }

  @override
  void onHorizontalDragEnd(DragEndDetails details) {
    onUp();
  }

  @override
  void tick(Canvas canvas, Size size, int current, int term) {
    const radius = BUTTON_SIZE / 2;
    canvas.drawCircle(Offset(x + radius, y + radius), radius, paint);
  }
}

Joystick class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
typedef MoveCallback = void Function(int direction);

class Joystick extends GameControl {
  final MoveCallback onMove;

  Joystick({required this.onMove});

  @override
  void onStart(Canvas canvas, Size size, int current) {
    getGameControlGroup()?.addControl(
        Button(
            onDown: () => onMove(BUTTON_POSITION_LEFT),
            onUp: () => onMove(0),
            direction: BUTTON_POSITION_LEFT
        )
    );

    getGameControlGroup()?.addControl(
        Button(
            onDown: () => onMove(BUTTON_POSITION_RIGHT),
            onUp: () => onMove(0),
            direction: BUTTON_POSITION_RIGHT
        )
    );
  }
}