基于鼠标事件计算相机的位置与旋转参数
相机环绕目标点控制实现记录
我正在开发相机环绕目标点的控制功能,下面是我的实现进展、踩过的坑以及对应的解决方案:
1. 计算鼠标方向[x, y]【已完成】
在鼠标移动事件里,通过对比上一帧和当前帧的鼠标位置,计算出鼠标移动的方向向量:
int directionX = lastPosition.x - position.x; int directionY = lastPosition.y - position.y;
2. 计算角度[theta, phi]【已完成】
一开始的角度计算没有限制俯仰范围,导致相机可能翻转到不合理的视角,后来做了Bug修复:
初始实现(存在视角越界问题)
float theta = fmod(lastTheta + sensibility * directionY, M_PI); float phi = fmod(lastPhi + sensibility * directionX * -1, M_PI * 2);
Bug修复后代码
float theta = lastTheta + sensibility * directionY * -1; if (theta < M_PI / -2) theta = M_PI / -2; else if (theta > M_PI / 2) theta = M_PI / 2; float phi = fmod(lastPhi + sensibility * directionX * -1, M_PI * 2);
3. 计算相机位置坐标[X,Y,Z]【已解决】
最初的坐标转换公式逻辑错误,导致相机位置计算不符合预期,感谢meowgoesthedog提供了正确的转换公式:
未成功的初始代码
float newX = radius * sin(phi) * cos(theta); float newY = radius * sin(phi) * sin(theta); float newZ = radius * cos(phi);
正确解决方案
float newX = radius * cos(theta) * cos(phi); float newY = radius * sin(theta); float newZ = radius * cos(theta) * sin(phi);
4. 计算相机旋转参数【已解决】
同样感谢meowgoesthedog给出的旋转参数计算方案,直接通过角度值转换就能得到正确的俯仰(pitch)和偏航(yaw)参数:
未完成的初始代码
float pitch = ?; float yaw = ?;
正确解决方案
float pitch = -theta; float yaw = -phi;

内容的提问来源于stack exchange,提问作者Max Mister
相关产品推荐
相关产品推荐

