相机与物体矢量相交的角度

Angle of camera to intersect with object vector

我正在尝试确定相机前向矢量与对象矢量相交的角度。

抱歉,以我的知识无法直接解释,请看附图: 相机可能没有直视物体(OBJ),我想知道角度(图中的?)相机的前向矢量(红色的 V1)与物体的矢量(红色的 V2)相交(如果相交),例如点 A、B、C 等取决于相机的 x 轴旋转。

我尝试计算红线 v1 和 v2 的归一化向量。 然后计算两个向量之间的夹角https://onlinemschool.com/math/library/vector/angl/ 但测试时结果与预期值不符

//v1
Vector3 hypoth = Camera.main.transform.forward.normalized;
//v2
Vector3 adjacent = (new Vector3(obj.transform.position.x, obj.transform.position.y, Camera.main.transform.position.z) 
                        -obj.transform.position).normalized;

float dotProd = Vector3.Dot(adjacent, hypoth);
float cosOfAngle = dotProd / (Vector3.Magnitude(adjacent) * Vector3.Magnitude(hypoth));
double radAngle = Math.Acos(cosOfAngle);
float angle = (float)((180 / Math.PI) * radAngle);

找到 v1v2 之间的角度给你这个角度,它与你在图表中标记的不匹配:

相反,求解 v1 与垂直于 v2 的平面之间的角度:

我们可以通过使用 Vector3.ProjectOnPlane, and then finding the angle between that projection and v1 using Vector3.Angle:

将 v1 投影到垂直于 v2 的平面来统一执行此操作
Vector3 projection = Vector3.ProjectOnPlane(hypoth, adjacent); 
float angle = Vector3.Angle(projection, hypoth);

我有一个类似的情况,我想将地形单位的碰撞雷达设置在与玩家喷气机相同的高度,同时它必须在相机的视线内,否则当你射击地形单位,子弹会看起来像穿过地面上的敌方单位,这仅在您使用前瞻性相机时有效,在正交上,您可能根本不需要这样做,只需将物体设置在相同的高度因为相机和所有东西都会对齐。

这是我的代码

 void SetColliderLocation()
{
    // Object on the ground
    A = TerrainUnit.transform.position;
    // Camera location
    B = cam.transform.position;
    // Enemy jet height 
    height = mainPlayerTransform.position.y;
    // Unit Vector normalized between A and B
    AB_Normalized = (A - B).normalized;
    // The unit vector required to move the collider to maintain its hieght and line of sight with the camera
    unitVector = (height - A.y) / AB_Normalized.y;
    // Setting the location of the collidar .
    collidarGameObject.transform.position = (AB_Normalized * unitVector) + A;
}

我希望它与您正在寻找的东西有些相似。

编辑:

如果你应用这个脚本而不是碰撞器你放一个盒子,你会看到盒子的位置总是在天空上的相机和地面上的物体之间,但是相机或地面上的物体正在移动.