我试图通过在身上施加力量来移动它。但是,它没有沿水平方向移动并形成轨迹,而是像我没有在其上施加力一样掉下来了。这是代码:
public class Box2dTest implements ApplicationListener
{
private OrthographicCamera camera;
World box2Dworld;
Box2DDebugRenderer debugRenderer;
private Body box2dBody;
Sprite ball_sprite;
SpriteBatch spriteBatch;
@Override
public void create()
{
camera = new OrthographicCamera();
camera.setToOrtho(false);
box2Dworld = new com.badlogic.gdx.physics.box2d.World(new Vector2(0.0F, -10.0F), true);
new BoundryWall(this.box2Dworld, new PointF(0.0F, 0.0F), 800.0F, camera);
debugRenderer = new Box2DDebugRenderer();
createDynamicBody(110f, 150f);
box2dBody.applyForce(new Vector2(30 * 1000, 0), box2dBody.getWorldCenter(), true);
Texture ball_in_hand_Texture = new Texture(Gdx.files.internal("test/ball_in_hand.png"));
ball_in_hand_Texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
ball_sprite = new Sprite(ball_in_hand_Texture);
ball_sprite.setPosition(110f, 150f);
spriteBatch = new SpriteBatch();
}
@Override
public void render()
{
Gdx.gl.glClearColor(0.5f, 0.5f, 0.5f, 1f);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
box2Dworld.step(1.0f/60.0f, 6, 2);
//box2Dworld.clearForces();
camera.update();
debugRenderer.render(box2Dworld, camera.combined);
spriteBatch.begin();
spriteBatch.draw(ball_sprite, 30 * box2dBody.getPosition().x, 30 * box2dBody.getPosition().y);
spriteBatch.end();
}
private void createDynamicBody(float x, float y)
{
// First we create a body definition
BodyDef bodyDef = new BodyDef();
// We set our body to dynamic, for something like ground which doesn't move we would set it to StaticBody
bodyDef.type = BodyType.DynamicBody;
bodyDef.bullet = true;
// Set our body's starting position in the world
// bodyDef.position.set(x / 60.0f, y / 60.0f);
//bodyDef.position.set(x / 30.0f, y / 30.0f);
bodyDef.position.set(x, y);
// Create our body in the world using our body definition
box2dBody = this.box2Dworld.createBody(bodyDef);
// Create a circle shape and set its radius to 6
CircleShape circle = new CircleShape();
circle.setRadius(10f);
// Create a fixture definition to apply our shape to
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = circle;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.6f; // Make it bounce a little bit
// Create our fixture and attach it to the body
Fixture fixture = box2dBody.createFixture(fixtureDef);
// Remember to dispose of any shapes after you're done with them!
// BodyDef and FixtureDef don't need disposing, but shapes do.
circle.dispose();
}
}
请帮我。我正在尝试从最近3天开始解决此问题,但无济于事。提前致谢。
最佳答案
我认为您已经创建了一个很大的世界,在该世界中施加该值的力将无效。实际上,由于box2d世界仅限于较低的值,因此施加任何值的力都将无效。
我已经很长时间没有在Box2d上工作了,但是我确实遇到了同样的问题。尝试在12x20左右的小世界中渲染精灵。然后尝试施加力,它一定会起作用。
关于java - 在box2d主体上施加力不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26138557/