The problem:
I succesfully implemented a shooting mechanism into my little game, but there is a problem.
The speed of the bullets are faster if my cursor is further from the player, and slower if the cursor is closer to the player.
So my question is: How can I make the bullets always go with the same speed?
Links:
The code (from Shot.java):
public Shot(World world, Camera camera, float x, float y, int width, int height, Color color, float targetX, float targetY) {
super(world, camera, x, y, width, height, color);
this.targetX = targetX;
this.targetY = targetY;
dx = targetX - x;
dy = targetY - y;
}
@Override
public void render(GameContainer gc, Graphics g) {
g.setColor(color);
g.fillOval(x - camera.getX(), y - camera.getY(), width, height);
}
@Override
public void update(GameContainer gc, int delta) {
x += dx * delta * .005f;
y += dy * delta * .005f;
}
I did it! Here is my solution (Thanks to Axis for help):
float dx, dy;
Vector2f vector;
public Shot(World world, Camera camera, float x, float y, float targetX, float targetY, int width, int height, Color color) {
super(world, camera, x, y, width, height, color);
dx = targetX - x;
dy = targetY - y;
vector = new Vector2f(dx, dy).normalise();
}
@Override
public void render(GameContainer gc, Graphics g) {
g.setColor(color);
g.fillOval(x - camera.getX(), y - camera.getY(), width, height);
}
@Override
public void update(GameContainer gc, int delta) {
x += vector.getX() * delta * 0.8f;
y += vector.getY() * delta * 0.8f;
}