const{ccclass,property}=cc._decorator;
@ccclass
export default class Player extends cc.Component{
private _rigidBody:cc.RigidBody;
private _onGroundB2Contacts:any[]=[];
private _isInAir:boolean=true;
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"];
//所有设置contact.disabled的代码写在此处
//检测落地(不在onBeginContact中写,因为设置contact.disabled时会导致出错)
let index=this._onGroundB2Contacts.indexOf(b2Contact);
if(index<0){
if(!contact.disabled&&!contact.disabledOnce&&!otherCollider.sensor&&contact.isTouching()){
let ny=-contact.getWorldManifold().normal.y;
if(ny>0.7){
this._onGroundB2Contacts.push(b2Contact);
if(this._isInAir){
this._isInAir=false;
//落地时
this.onDropGround();
}
}
}
}
}
private onEndContact(contact:cc.PhysicsContact,selfCollider:cc.PhysicsCollider,otherCollider:cc.PhysicsCollider):void{
let b2Contact=contact["_b2contact"];
let index=this._onGroundB2Contacts.indexOf(b2Contact);
if(index>-1)this._onGroundB2Contacts.splice(index,1);
if(this._onGroundB2Contacts.length<=0){
if(!this._isInAir){
this._isInAir=true;
//离开地面时
this.onLeaveGround();
}
}
}
private onDropGround():void{
}
private onLeaveGround():void{
}
}