Hey guys, been working out with Box2D in LibGDX, and I've been trying to create a bullet which will move accordingly towards wherever the mouse is pointed at. I have looked through multiple amounts of examples on finding out the angle, however it is not working out properly.
Code for Bullet Creation, in the Player entity:
Code:
@Override
public boolean touchDown(int x, int y, int pointer, int button) {
if (pointer == Buttons.LEFT) {
Bullet b = new Bullet(getGame());
float radians = (float)Math.atan2(y - (getBody().getPosition().y),
x - (getBody().getPosition().x));
b.realInit(getBody().getPosition().x + 2, getBody().getPosition().y - 0.1f, radians);
((GameState) game.getScreen()).addEntity("BULLET", b);
return true;
}
return true;
}
Afterwards, here is the whole Bullet class:
Code:
public class Bullet extends Entity {
public Bullet(DranithixGame world) {
super(0, 0, world, false);
}
@Override
public void init() {
}
public void realInit(float x, float y, float angle) {
Body b = getGame().bb.fixture(
getGame().fb.circleShape(0.1f).density(1f)).
type(BodyType.KinematicBody)
.angle(angle)
.bullet()
.build();
setBody(b);
getBody().setTransform(x, y, 0);
getBody().setUserData(this);
}
@Override
public void dispose() {
}
@Override
public void render(SpriteBatch sb) {
}
@Override
public void update(float f) {
getBody().setLinearVelocity(20, 0);
}
@Override
public void collide(Contact c) {
// if (c.getFixtureA().getBody().getUserData() instanceof Bullet) {
// Bullet b = (Bullet) c.getFixtureA().getBody().getUserData();
// b.setDead(true);
// } else if (c.getFixtureB().getBody().getUserData() instanceof Bullet) {
// Bullet b = (Bullet) c.getFixtureB().getBody().getUserData();
// b.setDead(true);
// }
}
}