CocosCreator 刚体与多边形碰撞器的单向碰撞(向上跳穿过时忽略碰撞)
const{ccclass,property}=cc._decorator;
@ccclass
export default class Player extends cc.Component{
private _rigidBody:cc.RigidBody;
private _disabledB2Contacts:any[]=[];
protected onLoad():void{
this._rigidBody=this.node.getComponent(cc.RigidBody);
this._rigidBody.enabledContactListener=true;//激活接触侦听
}
private onPreSolve(contact:cc.PhysicsContact,selfCollider:cc.PhysicsCollider,otherCollider:cc.PhysicsCollider):void{
let b2Contact=contact["_b2contact"];
let index=this._disabledB2Contacts.indexOf(b2Contact);
if(index>-1){
contact.disabled=true;
}else{
if(!contact.disabled&&!contact.disabledOnce&&!otherCollider.sensor&&contact.isTouching()){
let normal=contact.getWorldManifold().normal.mulSelf(-1);
if(normal.y<-0.7){
this._disabledB2Contacts.push(b2Contact);
contact.disabled=true;
}
}
}
}
private onEndContact(contact:cc.PhysicsContact,selfCollider:cc.PhysicsCollider,otherCollider:cc.PhysicsCollider):void{
let b2Contact=contact["_b2contact"];
let index=this._disabledB2Contacts.indexOf(b2Contact);
if(index>-1){
if(this.getAllB2ContactEnd(this._disabledB2Contacts)){
this._disabledB2Contacts.length=0;
}
}
}
private getAllB2ContactEnd(list:any[]):boolean{
let result=true;
for(let i=0,len=list.length;i<len;i++){
if(list[i].IsTouching()){
result=false;
break;
}
}
return result;
}
}
碰撞回调顺序:
...
Step
Step
BeginContact
PreSolve
PostSolve
Step
PreSolve
PostSolve
Step
PreSolve
PostSolve
Step
EndContact
Step
Step
...