In the game i am making i have run into a problem when it comes to using the mouse to fire bullets.
The bullets go in a completely different direction then what i want them to do.
You have probably had people with this problem several times, i have looked trough 3 of the posts on JG, but cant find an answer that helps me in there.
I am doing this in LibGDX.
These are the related methods;
Part of the InputProcessor in Player.java. (mouseMoved because i dont want to click at the moment, for testing.)
public boolean mouseMoved(int screenX, int screenY) {
this.mouseX = screenX - position.x / 2;
this.mouseY = screenY - position.y / 2;
this.dir = Math.atan2(mouseY, mouseX);
shoot();
return false;
}
Shoot method in Player.java
public void shoot() {
bullets.add(new Bullet(new Vector2(position.x, position.y), 350, dir));
}
Constructor in Bullet.java
double newX, newY;
public Bullet(Vector2 position, int SPEED, double dir) {
this.position = new Vector2(position.x, position.y);
Math.cos(dir);
this.newX = SPEED * Math.cos(dir);
this.newY = SPEED * Math.sin(dir);
}
Update method in Bullet.java
public void update() {
position.x += newX * Gdx.graphics.getDeltaTime();
position.y += newY * Gdx.graphics.getDeltaTime();
}
I am copying TheChernos way of doing it, and it works when in the game i have created in his tutorial.
These are the related stuff in that code. The difference i can see if where deltatime is added.
private void updateShooting() {
if (Mouse.getB() == 1) {
double dx = Mouse.getX() - Game.getWindowWidth() / 2;
double dy = Mouse.getY() - Game.getWindowHeight() / 2;
double dir = Math.atan2(dy, dx);
shoot(x, y, dir);
}
}
/////////////
public Projectile(int x, int y, double dir) {
xOrigin = x;
yOrigin = y;
angle = dir;
this.x = x;
this.y = y;
Math.cos(angle);
nx = speed * Math.cos(angle);
ny = speed * Math.sin(angle);
}
//////////
public void move() {
x += nx;
y += ny;
}
I also tried looking at ForeignGuyMikes Asteroids tutorial, but couldnt get that to work either.