问题:
我有这个“射击”类(class)。在代码中,目标变量是 mouseX 和 mouseY。 因此,当我单击鼠标按钮时,我的玩家类将创建一个新的射击对象。 但拍摄不准确。 如何计算正确的 dx 和 dy?
如果我将 dx 和 dy 添加到“子弹”的 x 和 y 中,子弹将移动到鼠标的方向。这就是我想要的。创建对象时,鼠标位置存储在 targetX 和 targetY 中。这就是椭圆想要达到的点。
链接:
代码(来自 Shot.java):
public class Shot extends Entity {
private float targetX, targetY;
public Shot(World world, float x, float y, int width, int height, Color color, float targetX, float targetY) {
super(world, x, y, width, height, color);
this.targetX = targetX;
this.targetY = targetY;
}
@Override
public void render(GameContainer gc, Graphics g, Camera camera) {
g.setColor(color);
g.fillOval(x - camera.getX(), y - camera.getY(), width, height);
}
@Override
public void update(GameContainer gc, int delta) {
float dx = targetX - x;
float dy = targetY - y;
x += dx * delta * .001f;
y += dy * delta * .001f;
}
}
我尝试了这个,但仍然不起作用:
@Override
public void update(GameContainer gc, int delta) {
float length = (float) Math.sqrt((targetX - x) * (targetX - x) + (targetY - y) * (targetY - y));
double dx = (targetX - x) / length * delta;
double dy = (targetY - y) / length * delta;
x += dx;
y += dy;
}
我做到了!这是我的解决方案:
问题是,目标是窗口的鼠标位置,而不是世界的鼠标位置。
这就是我计算世界鼠标位置的方法:
float mouseWorldX = x + (mouseX - screen_width / 2); // x = player's x position
float mouseWorldY = y + (mouseY - screen_height / 2); // y = player's y position
最佳答案
这是我游戏中的代码,用于在按下鼠标右键时将单位移动到鼠标:
length = Math.sqrt((target_X - player_X)*(target_X - player_X) + (target_Y - player_Y)*(target_Y - player_Y)); //calculates the distance between the two points
speed_X = (target_X - player_X) /length * player_Speed;
speed_Y = (target_Y - player_Y) /length * player_Speed;
这将以设定的速度将物体沿直线移动到目标。
编辑:这是我游戏中的实际代码
if(input.isMouseButtonDown(Input.MOUSE_RIGHT_BUTTON))
{
length = (float) Math.sqrt((player_waypoint_X - player_X)*(player_waypoint_X - player_X) + (player_waypoint_Y - player_Y)*(player_waypoint_Y - player_Y));
velocityX = (float) (player_waypoint_X - player_X) /length * (float) PlayerStats.player.db_player_Speed;
velocityY = (float) (player_waypoint_Y - player_Y) /length * (float) PlayerStats.player.db_player_Speed;
player_waypoint_X = input.getMouseX() - 2;
player_waypoint_Y = input.getMouseY() - 2;
}
出于测试目的,速度和长度在 init 方法中定义。每次按下鼠标右键,路径点的 X 和 Y 都会更改为鼠标位置。
我从这个问题中了解到这一点 velocity calculation algorithm。
关于java - 向鼠标方向射击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15909724/