java - 向鼠标方向射击

标签 java mouse slick2d

问题:

我有这个“射击”类(class)。在代码中,目标变量是 mouseX 和 mouseY。 因此,当我单击鼠标按钮时,我的玩家类将创建一个新的射击对象。 但拍摄不准确。 如何计算正确的 dx 和 dy?

如果我将 dx 和 dy 添加到“子弹”的 x 和 y 中,子弹将移动到鼠标的方向。这就是我想要的。创建对象时,鼠标位置存储在 targetX 和 targetY 中。这就是椭圆想要达到的点。

链接:

The game (finished)

代码(来自 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/

相关文章:

java - 如何使用 Java 将系统剪贴板内容粘贴到任意窗口

javascript - 在 Javascript 中处理相机式鼠标移动(启用连续鼠标移动)

java - 使用命令行设置 Eclipse 目标平台

java - Maven中库依赖的两个版本

c# - 鼠标左键弹起事件和openfiledialog

java - slick2d 中的子弹数组碰撞检测

java.lang.NoSuchMethodError : getPointer

java - 松开按键后停止动画

java - 如何在java中使用jackson将缺失的属性反序列化为默认值

delphi - 无法在设计时单击自定义控件