Best way to implement a simple bullet trajectory

Posted by AirieFenix on Game Development See other posts from Game Development or by AirieFenix
Published on 2014-06-11T15:09:37Z Indexed on 2014/06/11 15:43 UTC
Read the original article Hit count: 279

I searched and searched and although it's a fair simple question, I don't find the proper answer but general ideas (which I already have).

I have a top-down game and I want to implement a gun which shoots bullets that follow a simple path (no physics nor change of trajectory, just go from A to B thing).

simple draw of the vectors

a: vector of the position of the gun/player. b: vector of the mouse position (cross-hair). w: the vector of the bullet's trajectory.

So, w=b-a. And the position of the bullet = [x=x0+speed*time*normalized w.x , y=y0+speed*time * normalized w.y].

I have the constructor:

public Shot(int shipX, int shipY, int mouseX, int mouseY) {  
//I get mouse with Gdx.input.getX()/getY()
...      

  this.shotTime = TimeUtils.millis();

  this.posX = shipX;
  this.posY = shipY;

  //I used aVector = aVector.nor() here before but for some reason didn't work
  float tmp = (float) (Math.pow(mouseX-shipX, 2) + Math.pow(mouseY-shipY, 2));
  tmp = (float) Math.sqrt(Math.abs(tmp));

  this.vecX = (mouseX-shipX)/tmp;
  this.vecY = (mouseY-shipY)/tmp;
}

And here I update the position and draw the shot:

public void drawShot(SpriteBatch batch) {
  this.lifeTime = TimeUtils.millis() - this.shotTime;

  //position = positionBefore + v*t
  this.posX = this.posX + this.vecX*this.lifeTime*speed*Gdx.graphics.getDeltaTime();
  this.posY = this.posY + this.vecY*this.lifeTime*speed*Gdx.graphics.getDeltaTime();
...
}

Now, the behavior of the bullet seems very awkward, not going exactly where my mouse is (it's like the mouse is 30px off) and with a random speed. I know I probably need to open the old algebra book from college but I'd like somebody says if I'm in the right direction (or points me to it); if it's a calculation problem, a code problem or both. Also, is it possible that Gdx.input.getX() gives me non-precise position? Because when I draw the cross-hair it also draws off the cursor position.

Sorry for the long post and sorry if it's a very basic question. Thanks!

© Game Development or respective owner

Related posts about libgdx

Related posts about bullet-physics