UPDATEJBox2D + Slick2D - 不衝突
我有一個提示。這是因爲JBox2D屏幕的中心是(0, 0)
。這太奇怪了,因爲x
和y
不是從-1
到1,
它取決於屏幕尺寸。
這意味着我從互聯網複製的Util類(每個人都共享此代碼)不是最新的。我仍然需要幫助,因爲我找不到任何'算法'具有縱橫比+屏幕尺寸依賴性。
BASE問題
因爲我已經加入了「slick2D到jbox2D位置」,反之亦然(這就像在屏幕上的位置=屏幕/ 100位置JBox),我不明白一個好的結果。
public class Util {
private static final float SCALE = 0.01f; // 1/100 pixels
public static float toPosX(float posX) { return (posX * SCALE); }
public static float toPosY(float posY) { return (-posY * SCALE); }
public static float toScreenX(float posX) { return (posX/SCALE); }
public static float toScreenY(float posY) { return (-posY/SCALE); }
}
Square.java:
public class Square {
private Body body;
private Rectangle rectangle;
Square(World world, BodyType type, Vec2 pos, Vec2 size) {
float x = Util.toPosX(pos.x);
float y = Util.toPosY(pos.y);
float sx = Util.toPosX(size.x);
float sy = Util.toPosY(size.y);
//body definition
BodyDef bd = new BodyDef();
bd.position.set(x, y);
bd.type = type;
//define shape of the body.
PolygonShape cs = new PolygonShape();
cs.setAsBox(sx, sy);
//define fixture of the body.
FixtureDef fd = new FixtureDef();
fd.shape = cs;
fd.density = 1f;
fd.friction = 0.3f;
fd.restitution = 1.0f;
//create the body and add fixture to it
body = world.createBody(bd);
body.createFixture(fd);
rectangle = new Rectangle(0, 0, size.x, size.y);
rectangle.setLocation(pos.x, pos.y);
}
public Body getBody() { return this.body; }
public Rectangle getRectangle() { return this.rectangle; }
}
最後我的顯示類:下面
截圖我的代碼解釋
public class DisplayManager extends BasicGame {
private GameManager gameManager;
private Body b1, b2;
private Rectangle r1, r2;
private World world;
public DisplayManager(GameManager game) {
super("Title");
this.gameManager = game;
}
@Override
public void init(GameContainer container) throws SlickException {
this.gameManager.initPlayersSprites();
world = new World(new Vec2(0, -10));
Square s1, s2;
s1 = new Square(world, BodyType.STATIC, new Vec2(10, 800), new Vec2(1900, 30));
b1 = s1.getBody();
r1 = s1.getRectangle();
s2 = new Square(world, BodyType.DYNAMIC, new Vec2(945, 200), new Vec2(30, 30));
b2 = s2.getBody();
r2 = s2.getRectangle();
}
public void render(GameContainer container, Graphics g) throws SlickException {
float step = 1.0f/600.0f;
world.step(step, 6, 2);
r1.setLocation(Util.toScreenX(b1.getPosition().x), Util.toScreenY(b1.getPosition().y));
r2.setLocation(Util.toScreenX(b2.getPosition().x), Util.toScreenY(b2.getPosition().y));
g.draw(r1);
g.draw(r2);
}
}
下面是結果: 第一幀: http://i.stack.imgur.com/WgQPK.png
一些畫面之後: http://i.stack.imgur.com/a1XyL.png
(地上不動了,它只是一個截圖從我手裏拿着)
換句話說,立方體落下像永遠。我調試了立方體的位置,它不停下來。
使用Slick2D DebugDraw不會有幫助,因爲無論如何立方體都會穿過地面。
請注意,在JBox2D,它與像素測量(這是不準確的,但碰撞運作良好)