LayaAir3.x 物理2D碰撞事件
已挂载 Laya.RigidBody 的节点,可以直接挂载脚本并声明 onTriggerEnter、onTriggerStay、onTriggerExit 函数
const { regClass, property } = Laya;
@regClass()
export class PlayerBullet extends Laya.Script {
declare owner: Laya.Sprite;
private _body: Laya.RigidBody;
onAwake(): void {
this._body = this.owner.getComponent(Laya.RigidBody);
}
/** 3D物理触发器事件与2D物理碰撞事件,开始碰撞时执行 */
onTriggerEnter(other: Laya.PhysicsColliderComponent | Laya.ColliderBase, self?: Laya.ColliderBase, contact?: any): void {
let info = contact.getHitInfo();
// 取消碰撞
contact.SetEnabled(false);
// 获取碰撞平面的法线
console.log(info.normal.x info.normal.y);
}
/** 3D物理触发器事件与2D物理碰撞事件,持续碰撞时执行 */
onTriggerStay(other: Laya.PhysicsColliderComponent | Laya.ColliderBase, self?: Laya.ColliderBase, contact?: any): void {
}
/** 3D物理触发器事件与2D物理碰撞事件,结束碰撞时执行 */
onTriggerExit(other: Laya.PhysicsColliderComponent | Laya.ColliderBase, self?: Laya.ColliderBase, contact?: any): void {
}
}
如果是挂载脚本的节点的子节点添加 Laya.RigidBody 组件,此时用:bodyNode.on(Laya.Event.TRIGGER_ENTER, ...)
方法, 如:
this.bodyNode.on(Laya.Event.TRIGGER_ENTER, this, this.onTriggerEnter);
this.bodyNode.on(Laya.Event.TRIGGER_STAY, this, this.onTriggerStay);
this.bodyNode.on(Laya.Event.TRIGGER_EXIT, this, this.onTriggerExit);
// 不用时,使用 off() 移除侦听
//this.bodyNode.off(Laya.Event.TRIGGER_ENTER, this, this.onTriggerEnter);
//this.bodyNode.off(Laya.Event.TRIGGER_STAY, this, this.onTriggerStay);
//this.bodyNode.off(Laya.Event.TRIGGER_EXIT, this, this.onTriggerExit);
onTriggerEnter(other: Laya.PhysicsColliderComponent | Laya.ColliderBase, self?: Laya.ColliderBase, contact?: any):void{
console.log(contact);
}
onTriggerStay(other: Laya.PhysicsColliderComponent | Laya.ColliderBase, self?: Laya.ColliderBase, contact?: any): void {
}
onTriggerExit(other: Laya.PhysicsColliderComponent | Laya.ColliderBase, self?: Laya.ColliderBase, contact?: any): void {
}