需要一些帮助学习jbox2d

时间:2013-09-01 23:29:54

标签: java box2d playn jbox2d

首先非常感谢您的时间:)

我目前正在尝试了解jbox2d是如何工作的,而且我遇到了一些问题。我写的代码对我有意义,但应该有一些我根本不懂的东西。基本上我现在想做的是让主角(由玩家控制)与墙壁碰撞。

我没有太多细节,我有一个名为Player的动态实体类和一个名为Wall的静态实体类。我还有一个名为Map的类来处理关卡。 实体的坐标由屏幕中的像素表示。

现在这是关于jbox2d的部分

在类Map我有:

// ... other fields
private static final float TIME_STEP = 1.0f / 60.f;
private static final int VELOCITY_ITERATIONS = 6;
private static final int POSITION_ITERATIONS = 3;
private World world;

// constructor
public Map(int startPosX, int startPosY)
{
        // ...other stuffs
    Vec2 gravity = new Vec2(0, -10f);
    world = new World(gravity);
        // ...other stuffs
}

// update method that is called every 30 ms
public void update(int delta)
{
        // ...other stuffs
    world.step(TIME_STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
}

现在这就是静态实体的样子:

private Map map;
private Body body;
private Fixture fixture;
private PolygonShape shape;

public Wall(int x, int y, Map map)
{
    super(x, y);
    this.map = map;
    BodyDef bodyDef = new BodyDef();
    bodyDef.position.set(x, y);
    bodyDef.type = BodyType.STATIC;
    shape = new PolygonShape();
    shape.setAsBox(CELL_HEIGHT, CELL_WIDTH);
    FixtureDef fixtureDef = new FixtureDef(); 
    fixtureDef.shape = shape;
    body = map.getWorld().createBody(bodyDef);
    fixture = body.createFixture(fixtureDef);
}

最后是玩家:

private Map map;
private PolygonShape shape;
private Body body;
private Fixture fixture;

public MovingEntity(float x, float y, Map map)
{
    super.setX(x);
    super.setY(y);
    animation = Animation.IDLE;
    layer = graphics().createImmediateLayer(new EntityRenderer(this));
    layer.setVisible(false);
    graphics().rootLayer().add(layer);

    BodyDef bodyDef = new BodyDef();
    bodyDef.position.set(x, y);
    bodyDef.type = BodyType.DYNAMIC;
    shape = new PolygonShape();
    shape.setAsBox(getFrameSize().height(), getFrameSize().width());
    FixtureDef fixtureDef = new FixtureDef(); 
    fixtureDef.shape = shape;
    body = map.getWorld().createBody(bodyDef);
    fixture = body.createFixture(shape, 2.0f);
}
你们这些人我现在做错了什么?实体根本不会发生碰撞。此外,如果我尝试在我的更新方法中打印玩家身体的当前位置,即使我不移动,我也会改变坐标(我想它会因为引力而下降,我不需要在我的游戏)。

再次感谢!

1 个答案:

答案 0 :(得分:0)

我认为您的实体不会发生碰撞,因为您使用的是多边形形状。

shape = new PolygonShape();

您必须定义Polygone形状的点,以便jbox可以测试形状的碰撞。像这样:

Vec2[] vertices = {
                new Vec2(0.0f, - 10.0f),
                new Vec2(+ 10.0f, + 10.0f),
                new Vec2(- 10.0f, + 10.0f)
        };

        PolygonShape shape = new PolygonShape();
        shape.set(vertices, vertices.length);

此外,如果您不需要重力,则只需将重力矢量设置为0,0

Vec2 gravity = new Vec2(0f,0f);