You have to set the remodel of the Physique
to maneuver it to the desired coordinates:
physique.setTransform(place.x, place.y, physique.getAngle());
Doing that may snap the Physique
to the coordinates and offers you an correct approach of dragging the Physique
, however beware that the simulation may be unstable in some eventualities as you’re shifting issues explicity as a substitute of utilizing forces and velocities (normally it is effective although).
The complete supply for the instance above is:
public class SandboxGame extends ApplicationAdapter {
personal OrthographicCamera digicam;
personal World world;
personal Box2DDebugRenderer debugRenderer;
personal Physique physique;
personal Physique kinematicBody;
personal Physique floor;
personal Vector3 unprojectVector = new Vector3();
personal Vector2 worldTouchPosition = new Vector2();
@Override
public void create () {
float aspectRatio = (float)Gdx.graphics.getWidth() / Gdx.graphics.getHeight();
float w = 100.0f;
digicam = new OrthographicCamera(w, w / aspectRatio);
world = new World(new Vector2(0, -80), false);
debugRenderer = new Box2DDebugRenderer();
// Create physique
{
PolygonShape form = new PolygonShape();
form.setAsBox(4, 4);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.form = form;
fixtureDef.density = 1.0f;
BodyDef bodyDef = new BodyDef();
bodyDef.kind = BodyDef.BodyType.DynamicBody;
physique = world.createBody(bodyDef);
physique.createFixture(fixtureDef);
form.dispose();
}
// Create kinematic physique
{
PolygonShape form = new PolygonShape();
form.setAsBox(4, 2);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.form = form;
fixtureDef.density = 1.0f;
BodyDef bodyDef = new BodyDef();
bodyDef.kind = BodyDef.BodyType.KinematicBody;
kinematicBody = world.createBody(bodyDef);
kinematicBody.createFixture(fixtureDef);
kinematicBody.setTransform(-20, 0, 0);
form.dispose();
}
// Create floor
{
PolygonShape form = new PolygonShape();
form.setAsBox(100, 2);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.form = form;
fixtureDef.density = 1.0f;
BodyDef bodyDef = new BodyDef();
bodyDef.kind = BodyDef.BodyType.StaticBody;
floor = world.createBody(bodyDef);
floor.createFixture(fixtureDef);
floor.setTransform(0, -20, 0);
form.dispose();
}
Gdx.enter.setInputProcessor(new InputAdapter() {
public boolean touchDragged(int screenX, int screenY, int pointer) {
Vector2 place = unproject(screenX, screenY);
kinematicBody.setTransform(place.x, place.y, kinematicBody.getAngle());
return false;
}
});
}
@Override
public void render () {
world.step(Gdx.graphics.getDeltaTime(), 6, 6);
digicam.replace();
ScreenUtils.clear(Colour.BLACK);
debugRenderer.render(world, digicam.mixed);
}
personal Vector2 unproject(int screenX, int screenY) {
digicam.unproject(unprojectVector.set(screenX, screenY, 1));
worldTouchPosition.set(unprojectVector.x, unprojectVector.y);
return worldTouchPosition;
}
}