向鼠标方向射击

时间:2013-04-09 18:29:15

标签: java mouse slick2d

问题:

我有这个“镜头”课。在代码中,目标变量是mouseX和mouseY。 因此,当我单击鼠标按钮时,我的播放器类将创建一个新的镜头对象。 但枪击事件不准确。 如何计算正确的dx和dy?

如果我将dx和dy添加到“bullet”的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

2 个答案:

答案 0 :(得分:1)

这是我游戏中的代码,用于在按下鼠标右键时将单位移动到鼠标:

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

答案 1 :(得分:-1)

为了使子弹不是每次射击都改变方向,创建一个阵列列表,以便每个射击的子弹都有自己的x和y速度

相关问题