0
\$\begingroup\$

I want to shoot a bullet towards my mouse position but I think that my math is probably wrong since the position the bullets travel to isn't the right one. Here's my code

Vector2 bulletDirection = new Vector2(screenX - player.getX(), Gdx.graphics.getHeight() - (player.getY() - screenY)).nor();
bullet.setPosiion(player.getX(), player.getY());
bullet.translate(bulletDirection.x * flightSpeed, bulletDirection.y * flightSpeed);

Can you tell me what I'm doing wrong? The "bullet" object is my current bullet sprite

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Where do your bullets go instead? The more details you can give us about the symptoms, the better we can narrow down the cause. I do notice the order of terms in the y component of your Vector2 looks unusual. \$\endgroup\$
    – DMGregory
    Feb 28 '21 at 20:50
1
\$\begingroup\$

You are probably using Gdx.graphics.getHeight() to change orientation of vertical axis from recieved click. If this is the case following code should work correctly:

Vector2 bulletDirection = new Vector2(screenX - player.getX(), (Gdx.graphics.getHeight() - screenY) - player.getY()).nor();

Also there is better way using unproject described here as it will later solve problems with zooming and moving camera:

Vector3 touchPos = new Vector3(screenX, screenY, 0);
Vector3 unprojectedPos = camera.unproject(touchPos);
Vector2 bulletDirection = new Vector2(unprojectedPos.x - player.getX(), unprojectedPos.y - player.getY()).nor();
\$\endgroup\$
1
  • \$\begingroup\$ Thank you so much! \$\endgroup\$
    – xGolden
    Mar 1 '21 at 15:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .