发现个很奇怪的情况,碰撞检测的原理到底是怎样的,试了很久都不明白,真心求大佬解答。
项目中使用的是 基于Box2D的2D物理系统
我启用了
PhysicsSystem2D.instance.debugDrawFlags = EPhysics2DDrawFlags.Shape;
进行Debug
并且开启了碰撞回调
let collider = this.getComponent(Collider2D);
if (collider) {
collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
}
然后出现下图的这种情况。当发送碰撞的时候我会在控制台打印日志
检测到碰撞 控制台打印了信息
两个box明显重叠了,但没有碰撞 控制台没有打印了信息
将上面没有发送碰撞的放在一起,当僵尸同时接触两种碰撞 控制台打印了信息
预制体设置如下
相关代码
import { _decorator, Collider2D, Component, Contact2DType, Enum, EPhysics2DDrawFlags, IPhysics2DContact, Node, PhysicsSystem2D, Sprite, tween } from 'cc';
import { EnemisType } from '../EnumClass';
import { PeaBullet } from '../Plants/PeaBullet';
import { Plant } from '../Plants/Plant';
const { ccclass, property } = _decorator;
@ccclass('XiaoBing')
export class XiaoBing extends Component {
@property({ type: Enum(EnemisType) })
public EnemisType: EnemisType;
@property(Number)
public HP: number = 10;
@property(Number)
public Speed: number = 10;
private currHp: number;
private halfLife: boolean = true;
private stop: boolean = false;
protected onLoad(): void {
this.currHp = this.HP;
PhysicsSystem2D.instance.debugDrawFlags =
EPhysics2DDrawFlags.Shape;
}
start() {
let collider = this.getComponent(Collider2D);
if (collider) {
collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
}
}
onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
// 只在两个碰撞体开始接触时被调用一次
// 获取碰撞体所属节点的名字
let otherNode = otherCollider.node;
const otherNodeName = otherCollider.node.name;
console.log('Collided with:', otherNodeName);
// 判断碰撞体所属节点上是否挂载了某个脚本
if (otherNode.getComponent(PeaBullet)) {
console.log('遇到子弹');
let peaBullet = otherNode.getComponent(PeaBullet);
peaBullet.destroyBullet();
this.subHP(peaBullet.attVal);
} else if (otherNode.getComponent(Plant)) {
console.log('遇到植物');
let plant = otherNode.getComponent(Plant);
this.eatPlant(plant);
} else {
console.log('Collided with an unknown object');
}
}
eatPlant(plant: Plant) {
}
update(deltaTime: number) {
if (!this.stop) {
let pos = this.node.getPosition();
this.node.setPosition(pos.x - this.Speed * deltaTime, pos.y, 0);
}
}
subHP(attVal: number) {
this.currHp -= attVal;
if (this.HP / 2 == Math.round(this.currHp) && this.halfLife) {
this.halfLife = false;
this.halfLifeAnim();
}
if (this.currHp == 0) {
this.deadAnim();
}
}
halfLifeAnim() {
}
deadAnim() {
}
}