When you create a projectile keep a reference of the entity the projectile is shooting towards. Every update cycle, you need to do something like this.

Here is my rotation helper class for simple 2d rotation operations.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| 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); } } |

And vec2 class

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| 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; } } |

Here is a short guide how to do what you want.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public class Projectile { private Entity target; public void update() { float rotation = Rotation.angle(target.x, target.y, this.x, this.y); float speed = 2f; vec2 velocity = Rotation.point(vec2.NULL, new vec2(0, -speed), rotation); this.x+=velocity.x; this.y+=velocity.y; } } |