12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import Two from "two.js";
  2. import { scale, desginCageRadius, pedestalOffsetX, pedestalOffsetY, cageNum } from './design'
  3. import bulletImage from '@/assets/RoundaboutImage/2-13.png';
  4. // 子弹的核心逻辑
  5. export default ({two, center, speed, getGameState}) => {
  6. const _event = new Two.Events()
  7. // 子弹个数 = 轿厢个数
  8. const num = cageNum;
  9. // 子弹宽度 = 轿厢宽度
  10. const bulletRadius = desginCageRadius;
  11. // 子弹其实位置与底座是一致的
  12. const x = center.x + pedestalOffsetX * scale;
  13. const y = center.y + pedestalOffsetY * scale;
  14. // 弹夹
  15. let clip = [];
  16. // 在膛子弹
  17. let current = null;
  18. // 绘制子弹
  19. function drawBullets () {
  20. const bulletTexture = two.makeTexture(bulletImage);
  21. const list = Array(num).fill().map((_, inx) => {
  22. const arc = two.makeCircle(x, y, bulletRadius)
  23. arc.id = `bullet-${inx}`
  24. // arc.fill = 'black'
  25. arc.fill = bulletTexture
  26. arc.noStroke()
  27. arc.scale = scale;
  28. arc.visible = false; // 默认不显示, 即不上膛
  29. return arc
  30. })
  31. return list;
  32. }
  33. // 子弹上膛
  34. function bulletLoad() {
  35. current = clip.shift()
  36. if (current) {
  37. current.visible = true
  38. }
  39. }
  40. // 子弹飞行
  41. function fly() {
  42. if (!current) return;
  43. const { top, height } = current.getBoundingClientRect()
  44. current.position = new Two.Vector(current.position.x, current.position.y + speed)
  45. // 子弹飞行事件
  46. _event.dispatchEvent('shooting', {
  47. bullet: current,
  48. cancel: () => {
  49. two.removeEventListener('update', fly);
  50. _event.dispatchEvent('afterShoot');
  51. },
  52. })
  53. }
  54. // 射击
  55. function shoot() {
  56. if (getGameState() !== 1) return;
  57. _event.dispatchEvent('beforeShoot')
  58. two.addEventListener('update', fly)
  59. }
  60. // 弹夹
  61. clip = drawBullets()
  62. return {
  63. on: _event.on.bind(_event),
  64. bulletLoad,
  65. shoot,
  66. }
  67. }