@Override
public void create () {
world = new World(new Vector2(0, -9.81f), true);
renderer = new Box2DDebugRenderer();
camera = new OrthographicCamera();
batch = new SpriteBatch();
Gdx.input.setInputProcessor(this);
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.active = true;
//square
PolygonShape square = new PolygonShape();
square.setAsBox(50,50);
FixtureDef squareFixture = new FixtureDef();
squareFixture.density = 0.5f / 25;
squareFixture.friction = 0.5f;
squareFixture.shape = square;
squareFixture.restitution = 0.5f;
box = world.createBody(bodyDef);
Sprite boxSprite = new Sprite(new Texture(Gdx.files.internal("player.png")));
boxSprite.setSize(100,100);
boxSprite.setOrigin(boxSprite.getWidth() /2 , boxSprite.getHeight() / 2);
box.setUserData(boxSprite);
box.createFixture(squareFixture);
square.dispose();
@Override
public void render () {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
world.getBodies(tmpBodies);
for (Body body : tmpBodies){
if(body.getUserData() != null && body.getUserData() instanceof Sprite) {
Sprite sprite = (Sprite) body.getUserData();
sprite.setPosition(body.getPosition().x - sprite.getWidth() / 2, body.getPosition().y - sprite.getHeight() / 2);
sprite.setRotation(body.getAngle() * MathUtils.radiansToDegrees);
sprite.draw(batch);
}
}
batch.end();
world.step(1 / 60f, 8, 3);
renderer.render(world, camera.combined);
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
joint = null;
camera.unproject(tmp.set(screenX, screenY, 0));
world.QueryAABB(queryCallback, tmp.x, tmp.y, tmp.x, tmp.y);
if(joint == null){
randomSquareGenerator();
}
return true;
}
public void randomSquareGenerator(){
Random rand = new Random();
int n = rand.nextInt(5);
Vector2 mouseLoc = new Vector2(Gdx.input.getX()/scale - Gdx.graphics.getWidth()/(2 * scale), Gdx.graphics.getHeight()/(2 * scale) - Gdx.input.getY()/scale);
BodyDef bodyDef = new BodyDef();
bodyDef.position.set(mouseLoc);
bodyDef.type = BodyDef.BodyType.DynamicBody;
PolygonShape square = new PolygonShape();
square.setAsBox(25*n+1, 25*n+1);
box = world.createBody(bodyDef);
FixtureDef squareFixture = new FixtureDef();
squareFixture.density = 0.5f;
squareFixture.friction = 0.5f;
squareFixture.shape = square;
squareFixture.restitution = 1.0f;
boxSprite = new Sprite(new Texture(Gdx.files.internal("player.png")));
boxSprite.setSize(25*n + 1, 25*n + 1);
boxSprite.setPosition(box.getPosition().x - boxSprite.getWidth() / 2, box.getPosition().y - boxSprite.getHeight() / 2);
boxSprite.setRotation(box.getAngle() * MathUtils.radiansToDegrees);
box.setUserData(boxSprite);
box.createFixture(squareFixture);
square.dispose();
boxSprite.getTexture().dispose();
}