user2279603
user2279603

Reputation: 85

Java shoot towards mouse

I have a top down 2d game where you walk around shooting bad guys. I want to be able to shoot towards the mouse, no mater what direction it is but I have absolutely no idea how to do this.

Here is my bullet class:

public class bullet {

public double x, y,dy,dx,mx,my;
public int dir;

public Rectangle r = new Rectangle((int) x, (int) y, 5, 5);

public bullet(double x, double y) {
    this.x = x+10;
    this.y = y+10;
    this.mx = Comp.mx;
    this.my = Comp.my;
    r = new Rectangle((int) x, (int) y, 5, 5);
    if (x < mx+play.camx) {
        dx = 1;
    }
    if (x > mx+play.camx) {
        dx = -1;
    }
    if (y < my+play.camy) {
        dy = 1;
    }
    if (y > my+play.camy) {
        dy = -1;
    }
}

public void tick() {
    x+=dx;
    y+=dy;

    r = new Rectangle((int) x - play.camx, (int) y - play.camy, 5, 5);
}

public void render(Graphics g) {
    g.setColor(Color.black);
    g.fillRect((int) x - play.camx, (int) y - play.camy, 5, 5);
}
}

Upvotes: 0

Views: 1554

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347204

Basicially, you need calculate the angel between the start point and end point, something like...

angle = -Math.toDegrees(Math.atan2(startX - endX, startY - endY)) + 180;

As an example:

To track the mouse, use a MouseListener and MouseMotionListerner

Take a look at:

Upvotes: 2

Niklas
Niklas

Reputation: 375

Try using MouseInfo.getPointerInfo().getPosition() ( http://download.oracle.com/javase/1.5.0/docs/api/java/awt/PointerInfo.html#getLocation%28%29) It will return a point object. Use a timer and on every timer event you'll move your bullet a specific length (which you would want it to move) towards the mouse position provided by aforementioned method. You could do it like reducing difference of x- and y- Variables of mouse position and bullet position.

Upvotes: 0

Related Questions