背景:我正在创建一个AR寻宝应用程序。它很简单,它有一个定位器,告诉你宝藏相对于你的位置。我的相机是原点,宝藏是AR世界中的一个物体。
问题:,我想根据宝藏在太空中的位置旋转我的箭头。但在2d中。基本上,我会忽略相对前向平面,即camera.forward。
示例:如果相机旋转为默认值,则角度可以计算为atan2(dy,dx)。如果摄影机垂直向下看,则角度为atan2(dz,dx)。
我尝试过的东西:
Quaternion lookRot = Quaternion.LookRotation(target.transform.position - origin.transform.position);
Quaternion relativeRot = Quaternion.Inverse(origin.transform.rotation) * lookRot;相对旋转在3d空间中是正确的,但我想将其转换为2d,忽略camera.forward平面。因此,即使宝藏在相机的前面或后面,它也不应该改变角度。
发布于 2018-06-02 06:28:49
事实证明,有一种非常简单的方法可以获得目标的相对X和Y。
Vector2 ExtractRelativeXY(Transform origin, Transform target) {
// Get the absolute look rotation from origin to target.
Quaternion lookRot = Quaternion.LookRotation(target.transform.position - origin.transform.position);
// Create a relative look rotation with respect to origin's forward.
Quaternion relativeRot = Quaternion.Inverse(origin.transform.rotation) * lookRot;
// Obtain Matrix 4x4 from the rotation.
Matrix4x4 m = Matrix4x4.Rotate(relativeRot);
// Get the 3rd column (which is the forward vector of the rotation).
Vector4 mForward = m.GetColumn(2);
// Simply extract the x and y.
return new Vector2(mForward.x, mForward.y);
}得到x和y后,按照MBo和Tom的建议,使用angle = atan2(y,x)将其转换为角度。
这是因为四元数的矩阵分量可以在多个向量中演示。在这里可以找到更好的说明https://stackoverflow.com/a/26724912。
发布于 2018-06-01 01:31:14

好吧,所以我希望这是有意义的。你需要一些if语句来确定你的角色是沿着x,y还是z平面看的。希望图表能够清楚地说明这些参数是什么,但如果不是这样的话。例如,要在“x”平面上观察,y旋转必须在45°和-45°之间或135°和-135°之间,z旋转必须在45°和-45°之间或135°和-135°之间。
基本上,你得到的是一个球体被分成六个部分,每个角色可以沿着的平面有两个部分。一旦你确定了角色所在的平面,你就可以通过找出角色和宝藏在两个平面上的位置差异来确定方向。然后使用trig计算角度
发布于 2018-08-06 19:07:00
回复一个老帖子,但我正在努力解决同样的问题,并找到了一个相对简单的解决方案:
将目标位置(相对于原点)投影到由摄影机的前向向量定义的平面上。然后向投影点旋转:
Vector3 diff = target.transform.position - origin.transform.position;
Vector3 projected = Vector3.ProjectOnPlane(diff, Camera.main.transform.forward);
origin.transform.rotation = Quaternion.LookRotation(projected);https://stackoverflow.com/questions/50610635
复制相似问题