How to implement a simple bullet trajectory
- by AirieFenix
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).
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!