gpt4 book ai didi

Java向鼠标射击

转载 作者:行者123 更新时间:2023-12-02 05:08:27 25 4
gpt4 key购买 nike

我有一款自上而下的 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

看一下:

关于Java向鼠标射击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27554412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com