首先非常感谢您的时间:)
我目前正在尝试了解 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);
}
你们现在我做错了什么吗?实体根本不会发生碰撞。另外,如果我尝试在我的更新方法中打印玩家身体的当前位置,即使我不移动,坐标也会发生变化(我想它会因为重力而下降,我不需要游戏)。
再次非常感谢!