enemy.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import Animation from '../base/animation'
  2. import DataBus from '../databus'
  3. const ENEMY_IMG_SRC = 'images/enemy.png'
  4. const ENEMY_WIDTH = 60
  5. const ENEMY_HEIGHT = 60
  6. const __ = {
  7. speed: Symbol('speed')
  8. }
  9. let databus = new DataBus()
  10. function rnd(start, end){
  11. return Math.floor(Math.random() * (end - start) + start)
  12. }
  13. export default class Enemy extends Animation {
  14. constructor() {
  15. super(ENEMY_IMG_SRC, ENEMY_WIDTH, ENEMY_HEIGHT)
  16. this.initExplosionAnimation()
  17. }
  18. init(speed) {
  19. this.x = rnd(0, window.innerWidth - ENEMY_WIDTH)
  20. this.y = -this.height
  21. this[__.speed] = speed
  22. this.visible = true
  23. }
  24. // 预定义爆炸的帧动画
  25. initExplosionAnimation() {
  26. let frames = []
  27. const EXPLO_IMG_PREFIX = 'images/explosion'
  28. const EXPLO_FRAME_COUNT = 19
  29. for ( let i = 0;i < EXPLO_FRAME_COUNT;i++ ) {
  30. frames.push(EXPLO_IMG_PREFIX + (i + 1) + '.png')
  31. }
  32. this.initFrames(frames)
  33. }
  34. // 每一帧更新子弹位置
  35. update() {
  36. this.y += this[__.speed]
  37. // 对象回收
  38. if ( this.y > window.innerHeight + this.height )
  39. databus.removeEnemey(this)
  40. }
  41. }