如何使用LibGDX在Box2D中應用自動旋轉(如在現實世界中)?這看起來並不現實(見下圖)。LibGDX + Box2D旋轉
在現實世界中,該塊會旋轉並摔倒,但他們沒有在這個模擬。
世界已經Ÿ重力在-9.81(14:25和碰撞優良工程)這是代碼,我在那裏創建框:
PolygonShape pShape = new PolygonShape();
FixtureDef fDef = new FixtureDef();
BodyDef bDef = new BodyDef();
Body body;
pShape.setAsBox(width, height);
bDef.position.set(x, y);
bDef.type = type;
fDef.shape = pShape;
fDef.density = 1.0f;
fDef.friction = 0.3f;
body = world.createBody(bDef);
body.createFixture(fDef);
body.setUserData(this);
MassData md = new MassData();
md.mass = 5;
body.setMassData(md);
代碼主遊戲類:
public class Game implements ApplicationListener {
public static int WIDTH;
public static int HEIGHT;
World world;
Box2DDebugRenderer dr;
OrthographicCamera cam;
float time;
final float P = 1/60f;
final static int C = 100;
public void create() {
Gdx.gl.glClearColor(.1f, .1f, .1f, 1.0f);
WIDTH = Gdx.graphics.getWidth();
HEIGHT = Gdx.graphics.getHeight();
world = new World(new Vector2(0, -9.8f), false);
dr = new Box2DDebugRenderer();
cam = new OrthographicCamera();
cam.setToOrtho(false, WIDTH/C, HEIGHT/C);
new Block(world, BodyType.StaticBody, 2, HEIGHT, 0, HEIGHT);
new Block(world, BodyType.StaticBody, 2, HEIGHT, WIDTH-40, HEIGHT);
new Block(world, BodyType.StaticBody, WIDTH, 2, WIDTH, HEIGHT);
new Block(world, BodyType.StaticBody, WIDTH, 2, WIDTH, 0);
}
public void render() {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
input();
dr.render(world, cam.combined);
time += Gdx.graphics.getDeltaTime();
while(time >= P) {
update();
time -= P;
}
}
public void update() {
world.step(P, 5, 5);
}
public void input() {
if(Gdx.input.isTouched()) {
new Block(world, BodyType.DynamicBody, 50, 20, Gdx.input.getX(), HEIGHT-Gdx.input.getY());
}
}
public void dispose() { }
public void pause() { }
public void resize(int arg0, int arg1) { }
public void resume() { }
}
代碼塊類:
public class Block {
public Block(World world, BodyType type, float width, float height, float x, float y) {
PolygonShape pShape = new PolygonShape();
FixtureDef fDef = new FixtureDef();
BodyDef bDef = new BodyDef();
Body body;
pShape.setAsBox(width/Game.C, height/Game.C);
bDef.position.set(x/Game.C, y/Game.C);
bDef.type = type;
fDef.shape = pShape;
fDef.density = 1.0f;
fDef.friction = 0.3f;
body = world.createBody(bDef);
body.createFixture(fDef);
body.setUserData(this);
body.setFixedRotation(false);
MassData md = new MassData();
md.mass = 5;
body.setMassData(md);
}
}
你的身體有質量嗎? –
我已經打印出他們的值,他們有一個1公斤的質量。 – ViliX64
您是否設置了任何引力?你也可以鎖定旋轉身體,你可以這樣做嗎? – noone