java - 使用鼠标瞄准 LibGDX

标签 java 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);
}

最佳答案

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

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,上面已经完成了。

关于java - 使用鼠标瞄准 LibGDX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56092631/

相关文章:

android - 发布使用 Libgdx 创建的 apk

dialog - Libgdx - 如何让对话框淡出而不是整个舞台?

java - 将参数传递给不同的类时出现问题

java - 关闭连接 : next in java

java - AES 加密 : Encrypt using Arduino and decrypt using Java

java - 错误: [error] Source '__libgdx_setup_tmp\prj-common\src\MyGame.gwt.xml' does not exist

Java Android 滚动到底部并获取新数据后总是转到第一个数据/页面(顶部回收 View )

java - 我有两个几乎相同的方法,如何重构它们?

opengl - LibGDX 帧缓冲区混合

java - <LibGDX> 如何从同一文件加载多个纹理?