<template>
  <div class="game-scene" id="gameSceneWrap" ref="gameScene">
  </div>
</template>

<script>
import * as PIXI from 'pixi.js'
require('pixi-spine')

export default {
  name: 'gameScene',
  data () {
    return {
      wrapper: null,
      app: null
    }
  },
  methods: {
    loadSource () {
      PIXI.loader
        .add('bg', `textures/bg.jpg`)
        .add('spineCharacter', 'textures/people/60044.json')
        .load(this.loadedSource)
    },
    loadedSource () {
      this.initBg()
      this.initSpine()
    },
    initBg () {
      let cat = new PIXI.Sprite(PIXI.loader.resources.bg.texture)

      this.app.stage.addChild(cat)
    },
    initSpine () {
      let animation = new PIXI.spine.Spine(PIXI.loader.resources.spineCharacter.spineData)
      animation.x = 100
      animation.y = 200
      this.app.stage.addChild(animation)

      let style = new PIXI.TextStyle({
        fontFamily: 'Microsoft Yahei',
        fontSize: 32,
        fill: '#ffde00'
      })

      let message = new PIXI.Text('my name', style)
      message.anchor.x = 0.5
      message.x = animation.x
      message.y = animation.y - 180

      this.app.stage.addChild(message)

      if (animation.state.hasAnimation('walk1')) {
        animation.state.setAnimation(0, 'walk1', true)
        this.peopleWalk(animation, message)
      }
    },
    peopleWalk (animation, message) {
      this.app.ticker.add(delta => {
        this.walk(delta, animation, message)
      })
    },
    walk (delta, animation, message) {
      if (animation.x <= 50) {
        animation.scale.x = -1
      } else if (animation.x >= 500) {
        animation.scale.x = 1
      }
      animation.x -= animation.scale.x * 1
      message.x -= animation.scale.x * 1
    }
  },
  mounted () {
    this.wrapper = document.getElementById('gameSceneWrap')

    this.app = new PIXI.Application({ width: 604, height: 222, transparent: true })

    this.wrapper.appendChild(this.app.view)

    this.loadSource()
  }
}
</script>
<style lang="scss">
.game-scene{
    height: px2rem(222);
    margin: px2rem(20) 0;
    canvas{
        display: block;
        width: px2rem(604);
        height: 100%;
        margin: 0 auto;
    }
}
</style>
