C# 摄影机与对象向量相交的角度

C# 摄影机与对象向量相交的角度,c#,unity3d,angle,C#,Unity3d,Angle,我试图确定摄影机前向向量与对象向量相交的角度 很抱歉,根据我的知识,不能直接解释,请查看随附的图表:相机可能没有直接注视对象(OBJ),我想知道相机的前向矢量(V1为红色)与对象矢量(V2为红色)(如果有)相交的角度(?在图表中),例如点a、点B或点C,etc取决于摄像机的x轴旋转 我试着为红线v1和v2计算一个标准化向量。 然后计算两个向量之间的角度 但测试结果与预期值不符 //v1 Vector3 hypoth = Camera.main.transform.forward.normali

我试图确定摄影机前向向量与对象向量相交的角度

很抱歉,根据我的知识,不能直接解释,请查看随附的图表:相机可能没有直接注视对象(OBJ),我想知道相机的前向矢量(V1为红色)与对象矢量(V2为红色)(如果有)相交的角度(?在图表中),例如点a、点B或点C,etc取决于摄像机的x轴旋转

我试着为红线v1和v2计算一个标准化向量。 然后计算两个向量之间的角度 但测试结果与预期值不符

//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);

找到
v1
v2
之间的角度可以得到这个角度,它与图表中的标记不匹配:

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

我们可以通过使用将v1投影到垂直于v2的平面上,然后使用以下公式求出该投影与v1之间的角度来实现这一点:


我有一个类似的情况,我想将地形单位的准线设置在玩家喷气机的同一高度,同时必须在摄像机的视线范围内,否则当你射击地形单位时,子弹会像穿过地面上的敌人单位一样移动,这只适用于使用Prospecting camera时,在orthongal上,您可能根本不需要执行此操作,它只是将对象设置为与相机相同的高度,所有内容都将对齐

这是我的密码

 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;
}
我希望它和你要找的东西有多相似

编辑:


如果应用此脚本,而不是使用“碰撞器”放置一个长方体,您将看到长方体位置始终位于天空中的摄影机和地面上的对象之间,但摄影机或地面上的对象正在移动。

除非执行
(obj.transform.position-new Vector3),否则相邻的
不会指向obj(obj.transform.position.x、obj.transform.position.y、Camera.main.transform.position.z)).normalized;
?如果您解释了为什么需要角度-是否需要签名?如果需要,负角度表示什么?根据您对角度的意图,您甚至可能根本不需要计算角度。因为您已经用已知的90°角度绘制了它,您不能简单地执行
180f-90f-Vec吗tor3.角度(相机向前,(obj.位置-相机位置)。标准化)
Hi@ruzihm很抱歉耽搁了时间,当时正在外旅行,无法测试。您提出的解决方案有效,但我的物体高度不同,因此我的图表不准确,导致不一致。最后,我对相机前的物体进行了光线投射,这是一个足够好的解决方案-物体足够大。非常感谢您的帮助lp:)
 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;
}