BulletBase.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { _decorator, Component, js,Node, PhysicsRayResult, Vec3 } from 'cc';
  2. import { GunBase } from './GunBase';
  3. import { PoolManager } from '../../core/manager/PoolManager';
  4. import { Enemy } from '../../game/Enemy';
  5. import { ResUtil } from '../../utils/ResUtil';
  6. import { Game } from '../../game/Game';
  7. const { ccclass, property } = _decorator;
  8. @ccclass('BulletBase')
  9. export class BulletBase extends Component {
  10. public isDead: boolean = false;
  11. //枪的数据 在gunBase中
  12. public gunBase: GunBase = null!;
  13. //子弹自动回收的时间3s
  14. public recycleTime: number = 3;
  15. constructor(){
  16. super();
  17. this.isDead = false;
  18. }
  19. start() {
  20. this.scheduleOnce(this.autoRecycle.bind(this),this.recycleTime);
  21. }
  22. /**
  23. * 加入射击中的效果
  24. * @param e 碰撞到的结果
  25. */
  26. public addHitImpact(e:PhysicsRayResult) {
  27. ResUtil.loadRes("enemy/sundries/hit_impact", this.node)
  28. .then((impact: Node | null) => {
  29. if(impact){
  30. impact.worldPosition = e.hitPoint.add(e.hitNormal.multiplyScalar(0.01));
  31. impact.forward = e.hitNormal.multiplyScalar(-1);
  32. impact.setParent(e.collider.node,true);
  33. }
  34. this.scheduleOnce(()=>{
  35. if(impact.parent){
  36. PoolManager.putNode(impact);
  37. }
  38. },3);
  39. })
  40. .catch((error: Error) => {
  41. console.error("加载sundries/hit_impact异常", error);
  42. });
  43. }
  44. /**
  45. * 计算子弹用时
  46. */
  47. public getBulletTime(): number{
  48. let endWorldPos: Vec3 = Game.I.player.shootUI.getCrossHairPos();
  49. const bulletPos: Vec3 = this.node.position.clone();
  50. //计算3D空间距离 忽略Y轴
  51. const horizontalDistance = Vec3.distance(
  52. new Vec3(bulletPos.x, 0, bulletPos.z),
  53. new Vec3(endWorldPos.x, 0, endWorldPos.z)
  54. );
  55. //计算时间
  56. const minTime: number = 0.25;
  57. const factor: number = 5;
  58. return Math.max(horizontalDistance / (this.gunBase.data.bulletSpeed * factor), minTime);
  59. }
  60. /**
  61. * 自动回收子弹
  62. */
  63. public autoRecycle(){
  64. if(!this.isDead){
  65. this.isDead = true;
  66. PoolManager.putNode(this.node);
  67. }
  68. }
  69. }