0

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

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

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

现在这是关于 jbox2d 的部分

在班级地图中,我有:

// ... 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);
}

你们现在我做错了什么吗?实体根本不会发生碰撞。另外,如果我尝试在我的更新方法中打印玩家身体的当前位置,即使我不移动,坐标也会发生变化(我想它会因为重力而下降,我不需要游戏)。

再次非常感谢!

4

1 回答 1

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 重力 = 新 Vec2(0f, 0f);

于 2014-08-29T13:55:56.370 回答