如何防止碰撞中的两个物体同时穿过

How to prevent two objects in collisions from crossing both

我想知道如何防止一个物体穿过另一个物体。我有一个球和一个可以用鼠标移动的正方形。当我的球在我的正方形上时,我会移动它(例如在顶部)如果我走得很慢,如果不穿过它,球就会留在正方形上。

如果你的两个对象都定义了夹具,它们将无法相互交叉,这是一个必须如何创建受 BOX2D 世界物理影响的动态对象的示例,还有这个物体无法穿过传感器:

public Ball (World world){


        this.world = world;


        BodyDef bodyDef = new BodyDef();
        bodyDef.type = BodyType.DYNAMIC;
        bodyDef.position.set(0.0f/RATE, 0.0f/RATE);
        Ballbody = world.createBody(bodyDef);

        CircleShape circle = new CircleShape();
        radius = (int) (Math.random()*30+15); // you can set a non randum raduis 
        circle.m_radius = radius/RATE;

        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = circle;
        fixtureDef.restitution = 0.8f;
        fixtureDef.density = 2.0f;
        fixtureDef.friction = 0.3f;
        fixtureDef.filter.groupIndex = -1;
        Ballbody.createFixture(fixtureDef);
        Ballbody.getFixtureList().setUserData("Ballounaton"); // optional 

        Vec2 ballVec = new Vec2((float) (Math.random()*8+2),0.0f);
        Ballbody.setLinearVelocity(ballVec);

    }

确保为您的 box2d 动态或静态对象定义一个夹具,以避免像这个例子中那样穿过传感器:

FixtureDef fixtureDef = new FixtureDef();
            fixtureDef.shape = circle;
            fixtureDef.restitution = 0.8f;
            fixtureDef.density = 2.0f;
            fixtureDef.friction = 0.3f;
            fixtureDef.filter.groupIndex = -1;
            Ballbody.createFixture(fixtureDef);

根据 BOX2D 官方文档:

Recall that shapes don’t know about bodies and may be used independently of the physics simulation. Therefore Box2D provides the b2Fixture class to attach shapes to bodies. Fixtures hold the following:

  • a single shape
  • broad-phase proxies
  • density, friction, and restitution
  • collision filtering flags
  • back pointer to the parent body
  • user data
  • sensor flag