惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
Martin Fowler
Martin Fowler
B
Blog RSS Feed
D
DataBreaches.Net
L
LangChain Blog
月光博客
月光博客
S
SegmentFault 最新的问题
阮一峰的网络日志
阮一峰的网络日志
V
Visual Studio Blog
美团技术团队
Jina AI
Jina AI
博客园 - 司徒正美
雷峰网
雷峰网
Last Week in AI
Last Week in AI
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
IT之家
IT之家
博客园 - 三生石上(FineUI控件)
WordPress大学
WordPress大学
小众软件
小众软件
罗磊的独立博客
博客园_首页
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
A
About on SuperTechFans
Engineering at Meta
Engineering at Meta

博客园 - kingBook

git patch git 修改最后一次提交的日期 Win10 修改特定格式文件的右键快捷菜单 TypeScript async、 await、Promise LayaAir3.x 侦听程序退出 旋转力学例子 旋转力学公式 凹多边形碰撞检测 LayaAir3.x 侦听键盘事件 URP 阴影 TypeScript 里的 override TypeScript 类的自身类型 Unity 二维数组序列化 C# 匿名对象、动态属性 Cocos Creator 安卓模拟器中无法运行 Unity Editor 保存图片、缩放纹理 LayaAir3.2.0-beta.2 设置2d刚体线性速度,在不同设备(分辨率)下,表现不一致的问题 TypeScirpt 声明Map类型变量 TypeScript 声明函数类型变量
LayaAir3.x 物理2D碰撞事件
kingBook · 2024-07-26 · via 博客园 - kingBook

已挂载 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 {
    
}