HUNeater
HUNeater

Reputation: 166

Slick2d | Shooting with same speed

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 game (finished)

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;
}

Upvotes: 2

Views: 488

Answers (2)

Axis
Axis

Reputation: 846

First I would suggest switching to a vector class instead of splitting everything up into x and y. It will save you a lot of time in the long run.

All you need to do is change

public Shot(World world, Camera camera, Vector2 pos, int width, int height, Color color, Vector2 target) {
    super(world, camera, pos, width, height, color);
    this.target = target

    //dx = targetX - x; get rid of this
    //dy = targetY - y; and this

//add a vector called direction

this.direction = (target - pos).Normalize();
}

@Override
public void update(GameContainer gc, int delta) {

pos += direction * delta * bulletSpeed;
}

Upvotes: 1

phcoding
phcoding

Reputation: 608

Your problem is here:

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;
}

Your bullets speed is dependent on the distance from the target. Make it a constant value.

Upvotes: 1

Related Questions