繁体   English   中英

Java朝着老鼠射击

[英]Java shoot towards mouse

我有一个自上而下的2D游戏,您可以四处射击坏人。 我希望能够朝着鼠标射击,而不管它是什么方向,但是我绝对不知道如何做到这一点。

这是我的bullet班:

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);
}
}

基本上,您需要计算起点和终点之间的角度,例如...

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

举个例子:

若要跟踪鼠标,请使用MouseListenerMouseMotionListerner

看一眼:

尝试使用MouseInfo.getPointerInfo()。getPosition()( http://download.oracle.com/javase/1.5.0/docs/api/java/awt/PointerInfo.html#getLocation%28%29 )它将返回一个点对象。 使用一个计时器,在每个计时器事件中,您都将把子弹向上述方法提供的鼠标位置移动一个特定的长度(您希望它移动)。 您可以像减少鼠标位置和项目符号位置的x-和y-的差异那样来做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM