在做碰撞监听的时候,发现enabledContactListener=false和=true无法正常开关碰撞监听@官方 这应该是bug
想实现的效果:
拖拽移动一个物体时,关闭该物体的碰撞监听,释放手指时,打开监听,代码如下
实际的效果:
碰撞监听一直存在,enabledContactListener无法起到开关的作用
import { _decorator, Component,Collider,ICollisionEvent, Node,Vec3,Vec4, Sprite,Event,Button, SpriteFrame,tween, UITransform,Prefab,instantiate,EventTouch,EventMouse, input, Input, CircleCollider2D, PhysicsSystem2D, EPhysics2DDrawFlags, Contact2DType, Collider2D, RigidBody2D, director, } from ‘cc’;
const { ccclass, property } = _decorator;
@ccclass(‘test’)
export class test extends Component {
@property
private isDebug:boolean=false;
onLoad(){
PhysicsSystem2D.instance.enable=true;
if(this.isDebug){
PhysicsSystem2D.instance.debugDrawFlags=EPhysics2DDrawFlags.All;
}
else{
PhysicsSystem2D.instance.debugDrawFlags=EPhysics2DDrawFlags.None;
}
var c=this.node.getComponents(CircleCollider2D);
//console.log('组件名称'+c[0].name);
//console.log('组件名称'+c[1].name);
let flagCollision=this.node.getComponent(RigidBody2D).enabledContactListener;
flagCollision=false;
c[0].on (Contact2DType.BEGIN_CONTACT,this.bong1,this);
c[0].on (Contact2DType.STAY_CONTACT,this.bong2,this);
c[0].on (Contact2DType.END_CONTACT,this.bong3,this);
c[1].on (Contact2DType.BEGIN_CONTACT,this.bong1,this);
c[2].on (Contact2DType.BEGIN_CONTACT,this.bong1,this);
c[3].on (Contact2DType.BEGIN_CONTACT,this.bong1,this);
if (PhysicsSystem2D.instance) {
PhysicsSystem2D.instance.on(Contact2DType.BEGIN_CONTACT, this.bong1, this);
PhysicsSystem2D.instance.on(Contact2DType.STAY_CONTACT, this.bong2, this);
PhysicsSystem2D.instance.on(Contact2DType.END_CONTACT, this.bong3, this);
}// 注册全局碰撞回调函数
this.node.on(Node.EventType.TOUCH_MOVE,function(event){
const target = event.target as Node;
let flagCollision=target.getComponent(RigidBody2D).enabledContactListener;
flagCollision=false;
console.log("flagCollision="+flagCollision);
var moveXY=new Vec3;
var toXY=new Vec3;
moveXY.x=event.getDeltaX();//获取鼠标距离上一次事件移动的X距离
moveXY.y=event.getDeltaY();//获取鼠标距离上一次事件移动的Y距离
toXY.x=target.position.x + moveXY.x/1.5;
toXY.y=target.position.y + moveXY.y/1.8;
target.setPosition(toXY);
})
this.node.on(Node.EventType.TOUCH_END,function(event){
const target = event.target as Node;
let flagCollision=target.getComponent(RigidBody2D).enabledContactListener;
flagCollision=true;
})
}
start() {
}
private bong1(self,other){
console.log('发生碰撞',self,other);
console.log('碰撞的是'+self.tag);
}
private bong2(){
console.log('stay,stay');
}
private bong3(){
console.log('走出碰撞');
}
update(deltaTime: number) {
}
}