首页 > 解决方案 > 使用鼠标瞄准 LibGDX

问题描述

我在 libGDX 中制作游戏,但在设置 Bullet 类时遇到问题。我无法让弹丸进入鼠标位置。

我试图使用 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);
}

标签: javalibgdx

解决方案


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

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。无需再次乘以速度和 deltaTime,上面已经完成。


推荐阅读