I am making a top down shooter in Java and I need to be able to shoot in a line tangent to the mouse coordinates. In other words I need to be able to click my mouse and have a projectile spawn from my player, then move its position in a straight line in the direction of where I clicked. I have tried this already and I have failed miserably, and after looking into it for a while I haven't found a good answer. The code is pasted below, any ideas on what I'm doing wrong?
The mouse angle is calculated like this:
mouseAngle = (float) Math.toDegrees((float) Math.atan2(e.getY() - Player.getY(), e.getX() - Player.getX()));
VectorMath class
package vector;
public class VectorMath {
public VectorMath() {
}
public static void copyVector(Vector2f v1, Vector2f v2){
v1.setX(v2.getX());
v1.setY(v2.getY());
}
public static void printVector(Vector2f v){
System.out.println("x: " + v.getX() + " y: " + v.getY());
}
}
Projectile Class
package projectile;
import java.awt.Color;
import java.awt.Graphics2D;
import player.Mouse;
import player.Player;
import vector.Vector2f;
import vector.VectorMath;
public class Bullet {
private Vector2f pos = new Vector2f(0, 0);
private float x,y, xVel, yVel, moveSpeed = 0.1f, dX, dY;;
private float mouseAngle;
public Bullet(Vector2f pos) {
VectorMath.copyVector(this.pos, pos);
VectorMath.printVector(this.pos);
x = Player.getX();
y = Player.getY();
mouseAngle = Mouse.getMouseAngle();
}
public void update(){
xVel = pos.getX() + (((float)Math.cos(mouseAngle)) / moveSpeed);
yVel = pos.getY() + (((float)Math.sin(mouseAngle)) / moveSpeed);
dX = x + xVel;
dY = y + yVel;
x = dX;
y = dY;
}
public void render(Graphics2D g2){
g2.setColor(Color.green);
g2.fillRect((int)x, (int)y, 10, 10);
}
}