【问题标题】:Dynamic body is null in Box2dBox2d 中的动态主体为空
【发布时间】:2013-09-24 16:45:17
【问题描述】:

我有一个动态精灵和几个静态精灵。我的动态身体:

BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DynamicBody;

bodyDef.position.set(180, 20);
bodyMonkey = world.createBody(bodyDef);
PolygonShape abcBox = new PolygonShape(); 
bodyMonkey.setUserData(monkey1);
bodyMonkey.setFixedRotation(true);
abcBox.setAsBox(10.0f, 10.0f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = abcBox;
fixtureDef.density = 0.5f; 
fixtureDef.friction = 0.0f;
fixtureDef.restitution = 0.9f; 
Fixture fixture = bodyMonkey.createFixture(fixtureDef);
abcBox.dispose();
bodyMonkey.setLinearVelocity(new Vector2(1f, 0.5f));
bodyMonkey.setLinearDamping(1.0f);

我必须实现 ContactListener。我的班级:

@Override
public void beginContact(Contact contact) {
    Object a =  contact.getFixtureA().getBody().getUserData();
    Object b = contact.getFixtureB().getBody().getUserData();// null

    Gdx.app.log("1", ""+a);
    Gdx.app.log("2", ""+b);
    if(a!=null&&b!=null) {
        Gdx.app.log("ok", "");
        screen2dBox.restartGame();
    }
}

@Override
public void endContact(Contact contact) {
    // TODO Auto-generated method stub

}

@Override
public void preSolve(Contact contact, Manifold oldManifold) {
    // TODO Auto-generated method stub
}

@Override
public void postSolve(Contact contact, ContactImpulse impulse) {
    // TODO Auto-generated method stub
}

但对象 b 始终为空(a 不,b 是动态的,我在日志中看到了它)。我尝试使用 try、catch、finally 来克服这个问题(在 finally 块中 - screen2dBox.restartGame();),但我遇到错误,即联系人不能为空。不知道怎么解决?感谢您的帮助。

静态正文:

BodyDef bodyDefPlatform1 = new BodyDef();
     bodyDefPlatform1.type = BodyType.StaticBody;
     bodyDefPlatform1.position.set(50, 280);
     bodyPlatform1 = world.createBody(bodyDefPlatform1 );
     PolygonShape platformBox1 = new PolygonShape();  
     bodyPlatform1.setUserData(platform);
     platformBox1.setAsBox(20.0f, 10.0f);
     FixtureDef fixtureDefPlatform1 = new FixtureDef();
     fixtureDefPlatform1.shape = platformBox1;
     Fixture fixturePlatform = bodyPlatform1.createFixture( fixtureDefPlatform1);
    platformBox1.dispose();

【问题讨论】:

  • 你能发布任何静态体的初始化代码吗?

标签: java libgdx box2d collision-detection collision


【解决方案1】:

我检查了您的代码,我看不到任何错误。也许对象 monkey1 为空。

bodyMonkey.setUserData(monkey1); //check if monkey1 is null.

注意:我的声誉很低,我不能发表评论。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    相关资源
    最近更新 更多