File size: 2,530 Bytes
089f324
 
43854a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
089f324
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<!DOCTYPE html>
<html>
  <head>
    <title>Finite State Machine Demo</title>
    <script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
  </head>
  <body>
    <a-scene>
      <a-assets>
        <img id="groundTexture" src="https://cdn.aframe.io/a-painter/images/floor.jpg">
        <img id="skyTexture" src="https://cdn.aframe.io/a-painter/images/sky.jpg">
      </a-assets>

      <a-sky src="#skyTexture"></a-sky>

      <a-plane src="#groundTexture" rotation="-90 0 0" height="100" width="100"></a-plane>

      <a-entity id="player" position="0 1.5 -5" movement></a-entity>
    </a-scene>

    <script>
      AFRAME.registerComponent('movement', {
        init: function () {
          var el = this.el;
          var playerState = 'idle';

          // Set up the state machine
          var stateMachine = new StateMachine({
            init: 'idle',
            transitions: [
              { name: 'moveForward', from: ['idle', 'moveBackward'], to: 'moveForward' },
              { name: 'moveBackward', from: ['idle', 'moveForward'], to: 'moveBackward' },
              { name: 'stop', from: ['moveForward', 'moveBackward'], to: 'idle' }
            ],
            methods: {
              onEnterMoveForward: function () {
                el.setAttribute('animation', 'property: position; to: 0 1.5 -2; dur: 2000');
              },
              onEnterMoveBackward: function () {
                el.setAttribute('animation', 'property: position; to: 0 1.5 -8; dur: 2000');
              },
              onLeaveMoveForward: function () {
                el.setAttribute('animation', '');
              },
              onLeaveMoveBackward: function () {
                el.setAttribute('animation', '');
              }
            }
          });

          // Listen for keydown events to trigger state changes
          document.addEventListener('keydown', function (event) {
            switch (event.key) {
              case 'ArrowUp':
                stateMachine.moveForward();
                break;
              case 'ArrowDown':
                stateMachine.moveBackward();
                break;
            }
          });

          // Listen for keyup events to stop the player movement
          document.addEventListener('keyup', function (event) {
            switch (event.key) {
              case 'ArrowUp':
              case 'ArrowDown':
                stateMachine.stop();
                break;
            }
          });
        }
      });
    </script>
  </body>
</html>