在Java / Slick2D中射击子弹朝向鼠标位置

时间:2015-12-06 20:33:09

标签: java math mouseevent slick2d

我正在尝试实现一种朝向鼠标位置射击子弹的方法。我不知道它的数学或逻辑。这是一款2D自上而下的游戏。我的子弹向右射击并在某一点结束。我需要知道向鼠标位置发射的逻辑,而不是仅仅向x位置添加1。

2 个答案:

答案 0 :(得分:4)

使用atan2查找项目符号原点与鼠标光标之间的角度。然后使用Sin和Cos计算子弹的x和y速度。

伪代码

    public void ShootBullet()
    {
        double bulletVelocity = 1.0; //however fast you want your bullet to travel
        //mouseX/Y = current x/y location of the mouse
        //originX/Y = x/y location of where the bullet is being shot from
        double angle = Math.Atan2(mouseX - originX, mouseY - originY);
        double xVelocity = (bulletVelocity) * Math.Cos(angle);
        double yVelocity = (bulletVelocity) * Math.Sin(angle);
    }

答案 1 :(得分:0)

这是我产生射弹的代码。

    public void spawnProjectile(Input input) {

    double mouseX = 0;
    double mouseY = 0;
    double xVel;
    double yVel;
    double angle;

    if (timer > 0) {
        timer--;
    }

    if (input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON)) {
        mouseX = input.getMouseX();
        mouseY = input.getMouseY();
        if (projectiles.size() < 1 && timer <= 0) {
            projectiles.add(new Projectile((int) x + 8, (int) y + 8, 8, 8));
        }
    }

    if (projectiles.size() > 0) {
        for (int i = 0; i < projectiles.size(); i++) {
            projectiles.get(i).update(input);
            double originX = x;
            double originY = y;

            angle = Math.atan2(mouseX - originX, mouseY - originY);
            xVel = (bulletVel) * Math.cos(angle);
            yVel = (bulletVel) * Math.sin(angle);

            projectiles.get(i).x += xVel;
            projectiles.get(i).y += yVel;

            if (projectiles.get(i).timer == 0) {
                projectiles.remove();
            }
        }
    }
}