我想让坦克的炮塔在自上而下的视角下用鼠标瞄准。我写了一些代码来动画旋转到给定角度:
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;
}
}
但我不知道如何将它们组合在一起。应该怎么做?
最佳答案
您需要计算从左上角 (ULHC) 到炮塔中心 (CoT) 的角度以及从 ULHC 到鼠标位置的角度。接下来考虑由将 ULHC 连接到 CoT 的线、将 ULHC 连接到鼠标指针位置的线以及将 CoT 连接到鼠标指针位置的线形成的三角形。由于您知道从 ULHC 到 CoT 的距离以及从 ULHC 到鼠标指针位置的距离,您需要做的就是确定 CoT 的角度和鼠标指针位置之间的差异,您可以使用余弦定律来获取 ULHC 和炮塔鼠标位置之间的角度,以及从那里到您选择的任意轴的角度。
有图片会更简单:|
关于c++ - 带鼠标的自上而下透视瞄准坦克炮塔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31763773/