BulletBase.ts 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. */
  25. public enemyBlood(e:PhysicsRayResult){
  26. ResUtil.playParticle(
  27. `effects/Prefabs/blood`,
  28. 1,
  29. new Vec3(0.02,0.02,0.02),
  30. (blood) => {
  31. blood.active = true;
  32. blood.setParent(e.collider.node.parent);
  33. blood.worldPosition = e.hitPoint.add(e.hitNormal.multiplyScalar(0.01));
  34. blood.forward = e.hitNormal.multiplyScalar(-1);
  35. }
  36. );
  37. }
  38. /**
  39. * 加入射击中的效果
  40. * @param e 碰撞到的结果
  41. */
  42. public addHitImpact(e:PhysicsRayResult) {
  43. ResUtil.loadRes("enemy/sundries/hit_impact", this.node)
  44. .then((impact: Node | null) => {
  45. if(impact){
  46. impact.worldPosition = e.hitPoint.add(e.hitNormal.multiplyScalar(0.01));
  47. impact.forward = e.hitNormal.multiplyScalar(-1);
  48. impact.setParent(e.collider.node,true);
  49. }
  50. this.scheduleOnce(()=>{
  51. if(impact.parent){
  52. PoolManager.putNode(impact);
  53. }
  54. },3);
  55. })
  56. .catch((error: Error) => {
  57. console.error("加载sundries/hit_impact异常", error);
  58. });
  59. }
  60. /**
  61. * 计算子弹用时
  62. */
  63. public getBulletTime(): number{
  64. let endWorldPos: Vec3 = Game.I.player.shootUI.getCrossHairPos();
  65. const bulletPos: Vec3 = this.node.position.clone();
  66. //计算3D空间距离 忽略Y轴
  67. const horizontalDistance = Vec3.distance(
  68. new Vec3(bulletPos.x, 0, bulletPos.z),
  69. new Vec3(endWorldPos.x, 0, endWorldPos.z)
  70. );
  71. //计算时间
  72. const minTime: number = 0.25;
  73. const factor: number = 5;
  74. return Math.max(horizontalDistance / (this.gunBase.data.bulletSpeed * factor), minTime);
  75. }
  76. /**
  77. * 自动回收子弹
  78. */
  79. public autoRecycle(){
  80. if(!this.isDead){
  81. this.isDead = true;
  82. PoolManager.putNode(this.node);
  83. }
  84. }
  85. }