目录
之前做的是2.x版本的,最近切到了3.6,记录一下
项目-项目设置-功能剪裁

Box2D 物理模块需要先在 Rigidbody 中 开启碰撞监听,才会有相应的回调产生。本文只监听,不产生实际碰撞,选择了内置2D,没有添加Rigidbody2D组件
节点添加BoxCollider2D组件


注册方式:
Builtin 2D 物理模块只会发送 BEGIN_CONTACT 和 END_CONTACT 回调消息
创建脚本Player.ts
- import { _decorator, Component, Node, BoxCollider2D, Contact2DType, PhysicsSystem2D, Collider2D, IPhysics2DContact } from 'cc';
- const { ccclass, property } = _decorator;
-
- @ccclass('Player')
- export class Player extends Component {
-
- start() {
-
- // 注册单个碰撞体的回调函数
- let collider = this.getComponent(BoxCollider2D);
- if (collider) {
- // Builtin 2D 物理模块只会发送 BEGIN_CONTACT 和 END_CONTACT 回调消息。
- collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
- collider.on(Contact2DType.END_CONTACT, this.onEndContact, this);
- // collider.on(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
- // collider.on(Contact2DType.POST_SOLVE, this.onPostSolve, this);
- }
-
- // 注册全局碰撞回调函数
- if (PhysicsSystem2D.instance) {
- // Builtin 2D 物理模块只会发送 BEGIN_CONTACT 和 END_CONTACT 回调消息。
- PhysicsSystem2D.instance.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
- PhysicsSystem2D.instance.on(Contact2DType.END_CONTACT, this.onEndContact, this);
- // PhysicsSystem2D.instance.on(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
- // PhysicsSystem2D.instance.on(Contact2DType.POST_SOLVE, this.onPostSolve, this);
- }
- }
-
- /**
- * 只在两个碰撞体开始接触时被调用一次
- * @param selfCollider 指的是回调脚本的节点上的碰撞体
- * @param otherCollider 指的是发生碰撞的另一个碰撞体
- * @param contact 碰撞主要的信息, 位置和法向量, 带有刚体的本地坐标来,
- */
- onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
- console.log('onBeginContact');
-
- // contact.getWorldManifold在 Builtin 物理模块这个参数为空
- // const worldManifold = contact.getWorldManifold();
- // // 碰撞点数组
- // const points = worldManifold.points;
- // // 碰撞点上的法向量
- // const normal = worldManifold.normal;
- }
- onEndContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
- // 只在两个碰撞体结束接触时被调用一次
- console.log('onEndContact');
- }
- onPreSolve(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
- // 每次将要处理碰撞体接触逻辑时被调用
- console.log('onPreSolve');
- }
- onPostSolve(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
- // 每次处理完碰撞体接触逻辑时被调用
- console.log('onPostSolve');
- }
- }
-
当角色和金币相撞时触发

- // 节点名字和标签
- console.log(otherCollider.node.name);
- console.log(otherCollider.tag);
碰撞后消失的两种方法
- if (otherCollider.tag == 3) {
- // 不会从内存中释放, 默认传入false, 会清空节点上绑定的事件和 action
- // 文档:https://docs.cocos.com/creator/manual/zh/scripting/basic-node-api.html?h=removefromparent
- // otherCollider.node.removeFromParent();
-
- // 节点不再使用
- otherCollider.node.destroy();
- }