引自免费微信小程序:皆我百晓生
这个问题涉及到在Cocos Creator中处理碰撞关系的问题。你需要确保在onContactBegin回调函数中正确地删除子组件,这样可以防止子组件被错误地销毁。
首先,让我们修改enemy_01类以实现正确的碰撞关系管理:
class Enemy extends Sprite {
private _collider: Collider2D;
constructor() {
super();
this._collider = new Collider2D();
this.addEventListener(Event.ENTER_FRAME, this._handleCollision);
}
public get collider(): Collider2D {
return this._collider;
}
protected _handleCollision = () => {
if (!this.collider || !this.collisionComponent) {
return;
}
this.collisionComponent.destroy();
};
public destroy(): void {
super.destroy();
this.removeEventListener(Event.ENTER_FRAME, this._handleCollision);
}
}
接下来,我们将修改Bullet类以适当地添加一个销毁方法:
class Bullet extends Sprite {
private _collider: Collider2D;
constructor() {
super();
this._collider = new Collider2D();
this.addEventListener(Event.ENTER_FRAME, this._handleCollision);
}
public get collider(): Collider2D {
return this._collider;
}
protected _handleCollision = () => {
if (!this.collider || !this.collisionComponent) {
return;
}
this.collisionComponent.destroy();
};
public destroy(): void {
super.destroy();
this.removeEventListener(Event.ENTER_FRAME, this._handleCollision);
}
}
然后,我们将修改schedule函数以确保在销毁完成后调用destroy方法:
this.schedule(() => {
const enemy_01 = instantiate(this.enemy03);
this.ENEMY01.addChild(enemy_01);
enemy_01.destroy(); // 将此行添加到schedule中
enemy_01.addEventListener(Event.ENTER_FRAME, this._handleCollision); // 添加事件监听器以重置碰撞处理
}, 1);
最后,我们需要更新onContactBegin回调函数以销毁子弹对象:
const zidan = instantiate(this.bullet);
this.BULLET.addChild(zidan);
zidan.setPosition(x1, enemy_01.position.y - 70);//子弹位置依赖于飞机位置(报错位置)
const comp = enemy_01.getComponent(Collider2D);
comp.on(Contact2DType.BEGIN_CONTACT, (selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) => {
selfCollider.node.active = false; // 加入销毁逻辑
});
通过以上步骤,你应该能够在Cocos Creator中正确地处理碰撞关系,并且不再遇到错误。