Reputation:
i'm creating an android app(top-down shooter) on libgdx and have a problem with bullet positioning(No, with math for real)
So the problem is calculating a position of bullet
I want to spawn bullet here:
example
(where the red line is)
I calculating a position as:
bullet.setPosition(world.getPlayer().getX() + world.getPlayer().getWidth() * (float) Math.cos(Math.toRadians(world.getPlayer().getRotation())), world.getPlayer().getY() + world.getPlayer().getHeight() * (float) Math.sin(Math.toRadians(world.getPlayer().getRotation())));
And it works well while rotation = 0, but as soon as i start to rotate my player it goes wrong :(
Upvotes: 0
Views: 178
Reputation: 936
I am assuming that your player object is a libGDX Sprite
. Therefore, the getX
and getY
are the coordinates of the bottom-left corner of the sprite and the getRotation
is the rotation of the sprite about the origin (assumed to be at the centre of the player).
By doing some basic trigonometry you can convert the angle and a displacement to an (x,y) coordinate as you have attempted. The bullet needs to be rotated about the centre of the player. This can be done with the following code:
Sprite player = world.getPlayer(); //Just to tidy up the code
//Half width, half height and rotation
float hw = player.getWidth() / 2.0f;
float hh = player.getHeight() / 2.0f;
float rot = Math.toRadians(player.getRotation());
bullet.setPosition(player.getX() + hw + hw * (float) Math.cos(rot),
player.getY() + hh + hh * (float) Math.sin(rot));
Upvotes: 0