index.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  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. let 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 )
  46. disX = 0
  47. else if ( disX > screenWidth - this.width )
  48. disX = screenWidth - this.width
  49. if ( disY <= 0 )
  50. disY = 0
  51. else if ( disY > screenHeight - this.height )
  52. disY = screenHeight - this.height
  53. this.x = disX
  54. this.y = disY
  55. }
  56. /**
  57. * 玩家响应手指的触摸事件
  58. * 改变战机的位置
  59. */
  60. initEvent() {
  61. canvas.addEventListener('touchstart', ((e) => {
  62. e.preventDefault()
  63. let x = e.touches[0].clientX
  64. let y = e.touches[0].clientY
  65. //
  66. if ( this.checkIsFingerOnAir(x, y) ) {
  67. this.touched = true
  68. this.setAirPosAcrossFingerPosZ(x, y)
  69. }
  70. }).bind(this))
  71. canvas.addEventListener('touchmove', ((e) => {
  72. e.preventDefault()
  73. let x = e.touches[0].clientX
  74. let y = e.touches[0].clientY
  75. if ( this.touched )
  76. this.setAirPosAcrossFingerPosZ(x, y)
  77. }).bind(this))
  78. canvas.addEventListener('touchend', ((e) => {
  79. e.preventDefault()
  80. this.touched = false
  81. }).bind(this))
  82. }
  83. /**
  84. * 玩家射击操作
  85. * 射击时机由外部决定
  86. */
  87. shoot() {
  88. let bullet = databus.pool.getItemByClass('bullet', Bullet)
  89. bullet.init(
  90. this.x + this.width / 2 - bullet.width / 2,
  91. this.y - 10,
  92. 10
  93. )
  94. databus.bullets.push(bullet)
  95. }
  96. }