请教下为什么获取到了active但是不能设置

const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

rigi:cc.RigidBody=null;

onLoad () {
    this.rigi=this.node.getComponent(cc.RigidBody);
}

onBeginContact(contact:cc.PhysicsContact,selfCollider:cc.PhysicsCollider,otherCollider:cc.PhysicsCollider) {
    if(otherCollider.node.name=='foot'){
     //this.rigi.active = false;
      console.log(this.rigi); //能输出Rigidbody的信息
     console.log(this.rigi.active);//输出true

    }
 }

}
一个球和一个地面!但是设置刚体的active为false是提示box2d.js:7223
Uncaught Error
at b2Body.293.b2Body.SetActive (box2d.js:7223)
at cc_RigidBody.set [as active] (CCRigidBody.js:413)
at NewClass.onBeginContact (barrs.ts:15)
at PhysicsContact.129.PhysicsContact.emit (CCPhysicsContact.js:385)
at PhysicsContactListener._onBeginContact [as _BeginContact] (CCPhysicsManager.js:499)
at PhysicsContactListener.151.PhysicsContactListener.BeginContact (CCPhysicsContactListner.js:58)
at b2PolygonAndCircleContact.293.b2Contact.Update (box2d.js:11896)
at b2World.293.b2World.SolveTOI (box2d.js:21132)
at b2World.293.b2World.Step (box2d.js:20263)
at CCClass.update (CCPhysicsManager.js:213)

1赞

调用哪个 API 出现的问题?能给个 demo 吗?

cc.RigidBody没有active 属性
你写成this.rigi.node.active就可以了

ballgame - 副本.zip (534.3 KB)

这样的话小球直接就false了!

那些物理碰撞都是在一帧内计算的,所以你不能在一个碰撞周期内关掉RigidBody。解决方案有两个:

  • 用一个变量记录一下,下一帧再关掉,类似
onBeginContact(contact:cc.PhysicsContact,selfCollider:cc.PhysicsCollider,otherCollider:cc.PhysicsCollider) {
    if(otherCollider.node.name=='foot'){
         this.isTouchFoot = true;
    }
 }
update(dt: number) {
    if(this.isTouchFoot) {
        this.isTouchFoot = false;
        this.rigi.active = false;
    }
}
  • 高端骚操作,利用setTimeout将逻辑挤到下一帧
onBeginContact(contact:cc.PhysicsContact,selfCollider:cc.PhysicsCollider,otherCollider:cc.PhysicsCollider) {
    if(otherCollider.node.name=='foot'){
         setTimeout(() => {
            this.rigi.active = false;
        }, 0);
    }
 }
4赞

哦,对滴, 就是这个周期! 时间久了又忘了!谢谢!

得重点记录下了!

这两个 方法 哪个比较节约性能