【问题标题】:Top-down perspective aim tank turret with mouse带鼠标的自上而下透视瞄准坦克炮塔
【发布时间】:2015-08-01 16:31:04
【问题描述】:

我想让坦克的炮塔以自上而下的视角用鼠标瞄准。我已经编写了一些代码来动画旋转到给定的角度:

void Tank::rotateTurret(float angle) {
    turretRotation += angle;
}

sf::Sprite turret;
void Tank::update(unsigned int time) {
    if (turretRotation != 0.0f) {
        float rotate;

        if (turretRotation > 0.0f) {
            rotate = turretRotationSpeed * time;

            if (rotate > turretRotation) {
                rotate = turretRotation;
                turretRotation = 0;
            }
            else
                turretRotation -= rotate;
        }
        else {
            rotate = -turretRotationSpeed * time;

            if (rotate < turretRotation) {
                rotate = turretRotation;
                turretRotation = 0;
            }
            else
                turretRotation -= rotate;
        }

        turret.rotate(rotate);
    }
}

我可以计算鼠标指针相对于左上角的角度:

void TankPlayerController::update() {
    sf::Vector2i mousePosition = sf::Mouse::getPosition(*relativeWindow);
    sf::Vector2i mouseMovement = mousePosition - lastMousePosition;

    if (mouseMovement.x != 0 || mouseMovement.y != 0) {
        float mouseAngle = VectorAngleDeg(mousePosition.x, mousePosition.y);

        tank->rotateTurret(???);

        lastMousePosition = mousePosition;
    }
}

但我不知道如何将它们组合在一起。应该怎么做?

【问题讨论】:

  • 你会被炸飞的:(
  • 您可能需要考虑使用模数,以确保您的角度永远不会变得太大:#include &lt;cmath&gt;, turretRotation = std::fmod(turretRotation + angle, M_PI); 或使用其他获取 pi 的方式(例如 constexpr float pi() { return std::acos(-1.0f); })。尽管它在大多数库中都有定义,但我认为 M_PI 已经不在标准中了。

标签: c++ 2d game-engine sfml


【解决方案1】:

您需要计算从左上角 (ULHC) 到炮塔中心的角度 (CoT) 以及从 ULHC 到鼠标位置的角度。接下来考虑由将 ULHC 连接到 CoT 的线、将 ULHC 连接到鼠标指针位置的线以及将 CoT 连接到鼠标指针位置的线形成的三角形。因为您知道从 ULHC 到 CoT 的距离以及从 ULHC 到鼠标指针位置的距离,所以您需要做的就是确定到 CoT 的角度和鼠标指针位置之间的差异,您可以使用余弦定律获取 ULHC 和炮塔上鼠标位置之间的角度,以及从那里到您选择的任意轴的角度。

有图会更方便:|

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多