index.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. import Sprite from '../base/sprite'
  2. import Bullet from './bullet'
  3. import DataBus from '../databus'
  4. const screenWidth = window.innerWidth
  5. const screenHeight = window.innerHeight
  6. // 玩家相关常量设置
  7. const PLAYER_IMG_SRC = 'images/hero.png'
  8. const PLAYER_WIDTH = 80
  9. const PLAYER_HEIGHT = 80
  10. const databus = new DataBus()
  11. export default class Player extends Sprite {
  12. constructor() {
  13. super(PLAYER_IMG_SRC, PLAYER_WIDTH, PLAYER_HEIGHT)
  14. // 玩家默认处于屏幕底部居中位置
  15. this.x = screenWidth / 2 - this.width / 2
  16. this.y = screenHeight - this.height - 30
  17. // 用于在手指移动的时候标识手指是否已经在飞机上了
  18. this.touched = false
  19. this.bullets = []
  20. // 初始化事件监听
  21. this.initEvent()
  22. }
  23. /**
  24. * 当手指触摸屏幕的时候
  25. * 判断手指是否在飞机上
  26. * @param {Number} x: 手指的X轴坐标
  27. * @param {Number} y: 手指的Y轴坐标
  28. * @return {Boolean}: 用于标识手指是否在飞机上的布尔值
  29. */
  30. checkIsFingerOnAir(x, y) {
  31. const deviation = 30
  32. return !!(x >= this.x - deviation
  33. && y >= this.y - deviation
  34. && x <= this.x + this.width + deviation
  35. && y <= this.y + this.height + deviation)
  36. }
  37. /**
  38. * 根据手指的位置设置飞机的位置
  39. * 保证手指处于飞机中间
  40. * 同时限定飞机的活动范围限制在屏幕中
  41. */
  42. setAirPosAcrossFingerPosZ(x, y) {
  43. let disX = x - this.width / 2
  44. let disY = y - this.height / 2
  45. if (disX < 0) disX = 0
  46. else if (disX > screenWidth - this.width) disX = screenWidth - this.width
  47. if (disY <= 0) disY = 0
  48. else if (disY > screenHeight - this.height) disY = screenHeight - this.height
  49. this.x = disX
  50. this.y = disY
  51. }
  52. /**
  53. * 玩家响应手指的触摸事件
  54. * 改变战机的位置
  55. */
  56. initEvent() {
  57. canvas.addEventListener('touchstart', ((e) => {
  58. e.preventDefault()
  59. const x = e.touches[0].clientX
  60. const y = e.touches[0].clientY
  61. //
  62. if (this.checkIsFingerOnAir(x, y)) {
  63. this.touched = true
  64. this.setAirPosAcrossFingerPosZ(x, y)
  65. }
  66. }))
  67. canvas.addEventListener('touchmove', ((e) => {
  68. e.preventDefault()
  69. const x = e.touches[0].clientX
  70. const y = e.touches[0].clientY
  71. if (this.touched) this.setAirPosAcrossFingerPosZ(x, y)
  72. }))
  73. canvas.addEventListener('touchend', ((e) => {
  74. e.preventDefault()
  75. this.touched = false
  76. }))
  77. }
  78. /**
  79. * 玩家射击操作
  80. * 射击时机由外部决定
  81. */
  82. shoot() {
  83. const bullet = databus.pool.getItemByClass('bullet', Bullet)
  84. bullet.init(
  85. this.x + this.width / 2 - bullet.width / 2,
  86. this.y - 10,
  87. 10
  88. )
  89. databus.bullets.push(bullet)
  90. }
  91. }