Bullet.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { _decorator, Component, Node, Vec3, director, Collider2D, Contact2DType, IPhysics2DContact } from 'cc';
  2. import { GameManager } from './GameManager';
  3. const { ccclass, property } = _decorator;
  4. @ccclass('Bullet')
  5. export class Bullet extends Component {
  6. @property
  7. speed: number = 300;
  8. @property
  9. lifeTime: number = 5;
  10. private _target: Node = null;
  11. private _direction: Vec3 = new Vec3(0, 0, 0);
  12. private _gameManager: GameManager = null;
  13. start() {
  14. // 获取游戏管理器
  15. this._gameManager = director.getScene().getComponentInChildren(GameManager);
  16. // 设置生命周期
  17. this.scheduleOnce(() => {
  18. if (this.node && this.node.isValid) {
  19. this.node.destroy();
  20. }
  21. }, this.lifeTime);
  22. // 注册碰撞事件
  23. const collider = this.getComponent(Collider2D);
  24. if (collider) {
  25. collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  26. }
  27. }
  28. update(dt: number) {
  29. // 如果有目标,则追踪目标
  30. if (this._target && this._target.isValid) {
  31. // 计算朝向目标的方向
  32. const targetPos = this._target.position;
  33. this._direction = Vec3.subtract(new Vec3(), targetPos, this.node.position).normalize();
  34. }
  35. // 移动子弹
  36. const movement = new Vec3(
  37. this._direction.x * this.speed * dt,
  38. this._direction.y * this.speed * dt,
  39. 0
  40. );
  41. this.node.position = Vec3.add(new Vec3(), this.node.position, movement);
  42. }
  43. setTarget(target: Node) {
  44. this._target = target;
  45. // 初始化方向
  46. if (target && target.isValid) {
  47. this._direction = Vec3.subtract(new Vec3(), target.position, this.node.position).normalize();
  48. }
  49. }
  50. onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact) {
  51. // 检测是否与敌人碰撞
  52. if (otherCollider.node.name === 'Enemy') {
  53. // 销毁敌人
  54. if (this._gameManager) {
  55. this._gameManager.removeEnemy(otherCollider.node);
  56. }
  57. otherCollider.node.destroy();
  58. // 销毁子弹
  59. this.node.destroy();
  60. }
  61. // 检测是否与墙碰撞
  62. else if (otherCollider.node.name.includes('Wall')) {
  63. // 销毁子弹
  64. this.node.destroy();
  65. }
  66. }
  67. }