Im creating a side scroller that i need help with. I want the bullets to shoot towards the mouse. However, the current code I have only allows for shooting diagonally:
You’re going to need to use some trig to rotate bullets.
Here is my Rotation class. It basically hides some of the ugly looking maths and all.
public class Rotation {
public static int angle(vec2 pivot, vec2 point) {
float xdiff = pivot.x - point.x;
float ydiff = pivot.y - point.y;
float angle = (float) ((Math.atan2(xdiff, ydiff)) * 180 / Math.PI);
return -(int)angle;
}
public static float angle(float x0, float y0, float x1, float y1) {
return angle(new vec2(x0, y0), new vec2(x1, y1));
}
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);
}
}
angle() method will give you an angle between 2 points or something like that. Use this method to determine the rotation between player and the mouse.
point() method will rotate certain point around another point. After determining rotation between mouse and player, you will need to use this method to find by how much x and y should increase each frame.
To find the x, y speeds, you will need to do this:
Rotation.point(new vec2(0,0), new vec2(0, -speed), player.rotation);
The x and y will be the deltas to add to your bullets positions.
Here is vec2 class. pretty simple…
public class vec2 {
public static vec2 NULL = new vec2(0, 0);
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;
}
}