How to account for speed of the vehicle when shooting shells from it?

Posted by John Murdoch on Game Development See other posts from Game Development or by John Murdoch
Published on 2012-11-28T15:09:50Z Indexed on 2012/11/28 17:20 UTC
Read the original article Hit count: 358

Filed under:
|

I'm developing a simple 3D ship game using libgdx and bullet.

When a user taps the mouse I create a new shell object and send it in the direction of the mouse click. However, if the user has tapped the mouse in the direction where the ship is currently moving, the ship catches up to the shells very quickly and can sometimes even get hit by them - simply because the speed of shells and the ship are quite comparable.

I think I need to account for ship speed when generating the initial impulse for the shells, and I tried doing that (see "new line added"), but I cannot figure out if what I'm doing is the proper way and if yes, how to calculate the correct coefficient.

public void createShell(Vector3 origin, Vector3 direction, Vector3 platformVelocity, float velocity) {
    long shellId = System.currentTimeMillis(); // hack
    ShellState state = getState().createShellState(shellId, origin.x, origin.y, origin.z);
    ShellEntity entity = EntityFactory.getInstance().createShellEntity(shellId, state);

    add(entity);
    entity.getBody().applyCentralImpulse(platformVelocity.mul(velocity * 0.02f)); // new line added, to compensate for the moving platform, no idea how to calculate proper coefficient
    entity.getBody().applyCentralImpulse(direction.nor().mul(velocity));
}

private final Vector3 v3 = new Vector3();
public void shootGun(Vector3 direction) {
    Vector3 shipVelocity = world.getShipEntities().get(id).getBody().getLinearVelocity();
    world.getState().getShipStates().get(id).transform.getTranslation(v3); // current location of our ship
    v3.add(direction.nor().mul(10.0f)); // hack; this is to avoid shell immediately impacting the ship that it got shot out from  
    world.createShell(v3, direction, shipVelocity, 500);
}

© Game Development or respective owner

Related posts about physics

Related posts about bullet-physics