使用鼠标瞄准 LibGDX

Aiming in LibGDX using the mouse

我正在 libGDX 制作游戏,但在设置 Bullet class 时遇到问题。我无法让弹丸到达鼠标位置。

我曾尝试使用 Math.atan() 来找到我需要开火的角度,但我无法让它工作。现在我只是使用距离来找到 x 轴和 y 轴上的速度。

private static final int SPEED = 500;
private static Texture texture;
String path = "C:\Users\minicodcraft\Downloads\game\core\assets\";
private float x, y; // starting position
private float xVelocity, yVelocity;
private float yPos; // the y position of the mouse input
private float xPos; // the x position of the mouse input

public Bullet(float x, float y, float yPos, float xPos) {
    this.x = x;
    this.y = y;
    this.xPos = xPos;
    this.yPos = yPos;
    this.xVelocity = 0f;
    this.yVelocity = 0f;
    calcDirection();


    if (texture == null) {
        texture = new Texture(path + "Bullet.png");
    }
}

private void calcDirection() {
    float xDistanceFromTarget = Math.abs(xPos - x);
    float yDistanceFromTarget = Math.abs(yPos - y);
    float totalDistanceFromTarget = xDistanceFromTarget + yDistanceFromTarget;
    xVelocity = xDistanceFromTarget / totalDistanceFromTarget;
    yVelocity = yDistanceFromTarget / totalDistanceFromTarget;
    if (xPos < x) {
        xVelocity *= -1;
    }
    if (yPos < y) {
        yVelocity *= -1;
    }
}

public void update(float deltaTime) {
    if (x > 0 && y > 0) {
        x += xVelocity * SPEED * deltaTime;
        y += yVelocity * SPEED * deltaTime;
    } else if (x < 0 && y > 0) {
        x -= xVelocity * SPEED * deltaTime;
        y += yVelocity * SPEED * deltaTime;
    } else if (x > 0 && y < 0) {
        x += xVelocity * SPEED * deltaTime;
        y -= yVelocity * SPEED * deltaTime;
    } else if (x < 0 && y < 0) {
        x -= xVelocity * SPEED * deltaTime;
        y -= yVelocity * SPEED * deltaTime;
    }
}

public void render(SpriteBatch batch) {
    batch.draw(texture, x, y);
}

以下代码给出了从玩家位置到鼠标位置的速度:

float diffX = mouse.x - player.x;
float diffY = mouse.y - player.y;
float angle = (float) Math.atan2(diffY, diffX);
float velX = (float) (Math.cos(angle));
float velY = (float) (Math.sin(angle));
Vector2 velocity = new Vector2(velX, -velY);
velocity.nor();
velocity.scl(magnitudeSpeed);
velocity.scl(deltaTime);

那么velocity.x就是速度的x分量。分别为 y。不需要再乘以 speed 和 deltaTime,上面已经完成了。