LibGDX Projectile shooting

Hi all. I’ve done this a million times and I’ve always gotten it working, but whenever I try to replicate a technique I’ve used in a previous project to accomplish this it never works. I want to shoot a projectile in the direction of the player’s mouse cursor. I’m currently setting the projectile’s velocity by:


Vector2 vec = new Vector2(Gdx.input.getX() - getPos().x, Gdx.input.getX() - getPos().x);
float angle = (float) (Math.atan2(vec.y, vec.x));
getBody().setLinearVelocity(new Vector2(speed * MathUtils.cos(angle), speed * MathUtils.sin(angle)));

I’m not too good at vector math as I’m only 15 so I’m not sure if that’s even the correct way to do it, but it’s always worked for me.
The problem is that there are only two angles, 0.7853982 radians and -2.3561945 radians. So the projectile can only shoot in those two directions instead of all the possible directions.
I’m using LibGDX and Box2D, and I’m also in Ludum Dare 31 right now so I need an answer FAST.

So am I casting it weirdly, or do I need some Math.toDegrees’s?
Thanks everyone.

Not really sure what you mean by “only two angles”, but

Vector2 vec = new Vector2(Gdx.input.getX() - getPos().x, Gdx.input.getX() - getPos().x);

should be

Vector2 vec = new Vector2(Gdx.input.getX() - getPos().x, Gdx.graphics.getHeight() - Gdx.input.getY() - getPos().y);

Also, why not use the built-in methods of Vector2? You can do vec.angle() or vec.angleRad() to get the angle, and you can do

getBody().setLinearVelocity(vec.nor().scl(speed));

which normalizes the vector (same thing as setting x,y to cos,sin) and then multiplies both the x and the y by your speed.

I mean whenever I would shoot, there were only those two angles that the projectile shot in. Something to do with the way I was calculating the angle.

I did end up switching to the Vector2.angle() method for simplicity, which I avoided before because I forgot to use Math.toRadians.

Anyways it’s working now, so thank you.
But can I ask why you need to subtract the height of the window in the first part?

iirc, it’s because OpenGL coordinates are from the top down, while Gdx.input.getY() gets the y coordinate from the bottom of the screen, so you subtract to get actual coordinates. Another solution would be to use a Vector3 and camera.unproject().