我有一个自上而下的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;
举个例子:
Rotating a triangle around a point java
Java make a directed line and make it move
mouse motion listener only in one direction
Java: Move image towards mouse position
要跟踪鼠标,请使用
MouseListener
和MouseMotionListerner
看一眼:
How to write a MouseListener
How to write a MouseMotionListener
关于java - Java朝着老鼠射击,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27554412/