import { _decorator, Component, Node, Vec3, director, Collider2D, Contact2DType, IPhysics2DContact } from 'cc'; import { GameManager } from './GameManager'; const { ccclass, property } = _decorator; @ccclass('Bullet') export class Bullet extends Component { @property speed: number = 300; @property lifeTime: number = 5; private _target: Node = null; private _direction: Vec3 = new Vec3(0, 0, 0); private _gameManager: GameManager = null; start() { // 获取游戏管理器 this._gameManager = director.getScene().getComponentInChildren(GameManager); // 设置生命周期 this.scheduleOnce(() => { if (this.node && this.node.isValid) { this.node.destroy(); } }, this.lifeTime); // 注册碰撞事件 const collider = this.getComponent(Collider2D); if (collider) { collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this); } } update(dt: number) { // 如果有目标,则追踪目标 if (this._target && this._target.isValid) { // 计算朝向目标的方向 const targetPos = this._target.position; this._direction = Vec3.subtract(new Vec3(), targetPos, this.node.position).normalize(); } // 移动子弹 const movement = new Vec3( this._direction.x * this.speed * dt, this._direction.y * this.speed * dt, 0 ); this.node.position = Vec3.add(new Vec3(), this.node.position, movement); } setTarget(target: Node) { this._target = target; // 初始化方向 if (target && target.isValid) { this._direction = Vec3.subtract(new Vec3(), target.position, this.node.position).normalize(); } } onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact) { // 检测是否与敌人碰撞 if (otherCollider.node.name === 'Enemy') { // 销毁敌人 if (this._gameManager) { this._gameManager.removeEnemy(otherCollider.node); } otherCollider.node.destroy(); // 销毁子弹 this.node.destroy(); } // 检测是否与墙碰撞 else if (otherCollider.node.name.includes('Wall')) { // 销毁子弹 this.node.destroy(); } } }