Here comes the pro and jack of all trades! You’re sure to get stuff working now!
jk…
Ok… So lets say you have a rotation of the player, call it rotation.
Now you want to make 2 values: x,y of where the bullet will appear once shot from the gun at rotation 0. It shouldn’t be relative to the player… Just a position where it will spawn on the map.
You can make it appear on the top-right corner by doing something like:
float bullet_x = player.x + player.width;
float bullet_y = player.y;
This would make the bullet appear on top-right corner of the player when player is rotated 0 degrees.
Now, using my almighty Rotation class, we can calculate where the bullet should appear when player is actually rotated.
public class Rotation {
public static vec2 point(vec2 pivot, vec2 point, float rotation) {
float rot = (float)(1f / 180 * rotation * Math.PI);
float x = point.x - pivot.x;
float y = point.y - pivot.y;
float newx = (float)(x * Math.cos(rot) - y * Math.sin(rot));
float newy = (float)(x * Math.sin(rot) + y * Math.cos(rot));
newx += pivot.x;
newy += pivot.y;
return new vec2(newx, newy);
}
}
pivot is basically a point on which to around another point.
point is a position which needs to be rotated around the pivot.
Here is vec2…
public class vec2 {
public float x, y;
public vec2(float x, float y) {
this.x = x;
this.y = y;
}
public int getX() {
return (int) x;
}
public int getY() {
return (int) y;
}
}
Now we have all that we need.
To calculate were the bullet should appear rotated, we do something like this.
vec2 point = Rotation.point(new vec2(player.x + player.width / 2, player.y + player.height / 2), new vec2(bullet_x, bullet_y), rotation);
bullet_x = point.x;
bullet_y = point.y;
Gz, you should now have a bullet which should appear to be shooting from the gun…
One more thing… When you render the bullet, you need to rotate it around top-left corner, not around the center. Otherwise, you will have a strange position of the bullet depending on the player rotation.